import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getAuthTokens, authenticatedFetch } from '$lib/server/api';

export const GET: RequestHandler = async ({ params, url, cookies, fetch }) => {
    const { accessToken } = getAuthTokens(cookies);
    if (!accessToken) return json({ error: 'No autorizado' }, { status: 401 });

    const companyId = url.searchParams.get('company_id') || cookies.get('active_company_id');
    const id = params.id;

    if (!companyId) return json({ error: 'Compañía no seleccionada' }, { status: 400 });

    try {
        const response = await authenticatedFetch(
            `v1/a76/fda-catalog/${id}/lot-productions?company_id=${companyId}`,
            { method: 'GET', cache: 'no-store' },
            cookies, fetch
        );

        if (!response.ok) {
            return json({ error: 'Error al cargar lot productions' }, { status: response.status });
        }

        const data = await response.json();
        return json(data);
    } catch (error) {
        console.error('Error in lot-productions API:', error);
        return json({ error: 'Error de conexión' }, { status: 500 });
    }
};
