import { getServerApiUrl, getAuthTokens } from '$lib/server/api';
import type { PageServerLoad } from './$types';
import { redirect } from '@sveltejs/kit';

export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
	const parentData = await parent();
	const { accessToken } = getAuthTokens(cookies);
	if (!accessToken) {
		throw redirect(302, '/login');
	}

	const page = Number(url.searchParams.get('page')) || 1;
	const pageSize = Number(url.searchParams.get('page_size')) || 50;
	const sealFilter = url.searchParams.get('seal')?.trim() || '';

	const cookieCompanyId = cookies.get('active_company_id');
	const companyId = cookieCompanyId
		? parseInt(cookieCompanyId)
		: parentData.companies?.[0]?.id;

	if (!companyId) {
		return {
			seals: { items: [], total: 0, page, page_size: pageSize, pages: 0 },
			error: 'Selecciona una compañía para ver los sellos',
			status: 400
		};
	}

	const apiUrl = getServerApiUrl();
	const query = new URLSearchParams({
		page: page.toString(),
		page_size: pageSize.toString(),
		company_id: companyId.toString()
	});
	if (sealFilter) {
		query.set('seal', sealFilter);
	}

	const endpoint = `${apiUrl}v1/a76/seals/?${query.toString()}`;

	try {
		const response = await fetch(endpoint, {
			headers: {
				Authorization: `Bearer ${accessToken}`
			}
		});

		if (!response.ok) {
			let errorMessage = `Error: ${response.status} ${response.statusText}`;
			try {
				const errorData = await response.json();
				errorMessage = errorData.detail || errorData.message || errorMessage;
			} catch {
				// not JSON
			}
			return {
				seals: { items: [], total: 0, page, page_size: pageSize, pages: 0 },
				error: errorMessage,
				status: response.status
			};
		}

		const data = await response.json();
		return {
			seals: {
				items: data.items,
				total: data.total,
				page: data.page,
				page_size: data.page_size,
				pages: data.pages
			},
			status: 200
		};
	} catch (error: unknown) {
		console.error('Error fetching seals:', error);
		const message = error instanceof Error ? error.message : 'Failed to connect to server';
		return {
			seals: { items: [], total: 0, page, page_size: pageSize, pages: 0 },
			error: message,
			status: 500
		};
	}
};
