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

// Helper to log to a file for debugging
const debugLog = (msg: string) => {
    try {
        const timestamp = new Date().toISOString();
        fs.appendFileSync('/tmp/fda_proxy_debug.log', `[${timestamp}] ${msg}\n`);
    } catch (e) { }
};

// Precise cleaners to ensure only business data is sent to backend
const cleanFDA01 = (d: any) => {
    if (!d) return null;
    return {
        prod_code: d.prod_code || null,
        commodity_desc: d.commodity_desc || null,
        brand_name: d.brand_name || null,
        disclaimer: d.disclaimer || null,
        pgm_code: d.pgm_code || null,
        proc_code: d.proc_code || null,
        intnd_use_code: d.intnd_use_code || null,
        intnd_use_desc: d.intnd_use_desc || null,
        temp_qual: d.temp_qual || null,
        temp_type: d.temp_type || null,
        temp_degrees: d.temp_degrees || null,
        temp_negative: d.temp_negative || null,
        temp_location: d.temp_location || null,
        quantity_1: d.quantity_1 || null,
        qty_uom_1: d.qty_uom_1 || null,
        quantity_2: d.quantity_2 || null,
        qty_uom_2: d.qty_uom_2 || null,
        quantity_3: d.quantity_3 || null,
        qty_uom_3: d.qty_uom_3 || null,
        ctry_prod: d.ctry_prod || null,
        ctry_source: d.ctry_source || null,
        ctry_growth: d.ctry_growth || null,
        ctry_refusal: d.ctry_refusal || null,
        ctry_shipping: d.ctry_shipping || null,
        manuf_key: d.manuf_key || null,
        shipper_key: d.shipper_key || null,
        ult_cons_key: d.ult_cons_key || null,
        fda_imp_key: d.fda_imp_key || null,
        pn_subm_key: d.pn_subm_key || null,
        consol_key: d.consol_key || null,
        producer_key: d.producer_key || null,
        owner_key: d.owner_key || null,
        deli_party_key: d.deli_party_key || null,
        grower_key: d.grower_key || null,
        dev_ini_imp_key: d.dev_ini_imp_key || null,
        lacf_cont_1: d.lacf_cont_1 || null,
        lacf_cont_2: d.lacf_cont_2 || null,
        lacf_cont_3: d.lacf_cont_3 || null,
        pn_transmitter_key: d.pn_transmitter_key || null
    };
};

const cleanFDA23 = (d: any) => ({
    line: typeof d.line === 'number' ? d.line : (parseInt(d.line) || 1),
    aoc_code: d.aoc_code || '',
    aoc_qual: d.aoc_qual || null
});

const cleanFDA04 = (d: any) => ({
    line: typeof d.line === 'number' ? d.line : (parseInt(d.line) || 1),
    ele_name: d.ele_name || '',
    ele_qty: (d.ele_qty === '' || d.ele_qty === null || d.ele_qty === undefined) ? null : parseFloat(d.ele_qty),
    ele_qty_uom: d.ele_qty_uom || null,
    ele_pctg: (d.ele_pctg === '' || d.ele_pctg === null || d.ele_pctg === undefined) ? null : parseFloat(d.ele_pctg)
});

const cleanFDA25 = (d: any) => ({
    line: typeof d.line === 'number' ? d.line : (parseInt(d.line) || 1),
    lot_number: d.lot_number || '',
    production_start_date: d.production_start_date || null,
    production_end_date: d.production_end_date || null
});

async function saveNestedData(id: string, companyId: string, nested: any, cookies: any, fetch: any) {
    debugLog(`saveNestedData started for id: ${id}`);
    const { fda01, fda23_codes, fda04_elements, fda25_lots } = nested;

    // 1. FDA01 Specifications
    if (fda01) {
        debugLog(`Saving FDA01`);
        const res = await authenticatedFetch(
            `v1/a76/fda-catalog/${id}/specifications?company_id=${companyId}`,
            { method: 'PUT', body: JSON.stringify(cleanFDA01(fda01)) },
            cookies, fetch
        );
        if (!res.ok) {
            const txt = await res.text();
            debugLog(`Error FDA01: ${res.status} - ${txt}`);
            throw new Error(`Error en FDA01: ${res.status} - ${txt}`);
        }
    }

    // 2. FDA23 Affirmation Codes
    debugLog(`Processing FDA23`);
    const resExist23 = await authenticatedFetch(`v1/a76/fda-catalog/${id}/affirmation-codes?company_id=${companyId}`, { method: 'GET' }, cookies, fetch);
    if (resExist23.ok) {
        const items = await resExist23.json();
        debugLog(`Deleting ${items.length} existing FDA23 items`);
        for (const item of items) {
            await authenticatedFetch(`v1/a76/fda-catalog/${id}/affirmation-codes/${item.id}?company_id=${companyId}`, { method: 'DELETE' }, cookies, fetch);
        }
    }
    if (fda23_codes && Array.isArray(fda23_codes)) {
        for (const code of fda23_codes) {
            if (!code.aoc_code) continue;
            const res = await authenticatedFetch(`v1/a76/fda-catalog/${id}/affirmation-codes?company_id=${companyId}`, { method: 'POST', body: JSON.stringify(cleanFDA23(code)) }, cookies, fetch);
            if (!res.ok) {
                const txt = await res.text();
                debugLog(`Error FDA23: ${res.status} - ${txt}`);
                throw new Error(`Error en FDA23: ${res.status} - ${txt}`);
            }
        }
    }

    // 3. FDA04 Constituent Elements
    debugLog(`Processing FDA04`);
    const resExist04 = await authenticatedFetch(`v1/a76/fda-catalog/${id}/constituent-elements?company_id=${companyId}`, { method: 'GET' }, cookies, fetch);
    if (resExist04.ok) {
        const items = await resExist04.json();
        debugLog(`Deleting ${items.length} existing FDA04 items`);
        for (const item of items) {
            await authenticatedFetch(`v1/a76/fda-catalog/${id}/constituent-elements/${item.id}?company_id=${companyId}`, { method: 'DELETE' }, cookies, fetch);
        }
    }
    if (fda04_elements && Array.isArray(fda04_elements)) {
        for (const ele of fda04_elements) {
            if (!ele.ele_name) continue;
            debugLog(`Saving FDA04 item: ${ele.ele_name}`);
            const res = await authenticatedFetch(`v1/a76/fda-catalog/${id}/constituent-elements?company_id=${companyId}`, { method: 'POST', body: JSON.stringify(cleanFDA04(ele)) }, cookies, fetch);
            if (!res.ok) {
                const txt = await res.text();
                debugLog(`Error FDA04: ${res.status} - ${txt}`);
                throw new Error(`Error en FDA04: ${res.status} - ${txt}`);
            }
        }
    }

    // 4. FDA25 Lot Productions
    debugLog(`Processing FDA25`);
    const resExist25 = await authenticatedFetch(`v1/a76/fda-catalog/${id}/lot-productions?company_id=${companyId}`, { method: 'GET' }, cookies, fetch);
    if (resExist25.ok) {
        const items = await resExist25.json();
        debugLog(`Deleting ${items.length} existing FDA25 items`);
        for (const item of items) {
            await authenticatedFetch(`v1/a76/fda-catalog/${id}/lot-productions/${item.id}?company_id=${companyId}`, { method: 'DELETE' }, cookies, fetch);
        }
    }
    if (fda25_lots && Array.isArray(fda25_lots)) {
        for (const lot of fda25_lots) {
            if (!lot.lot_number) continue;
            const res = await authenticatedFetch(`v1/a76/fda-catalog/${id}/lot-productions?company_id=${companyId}`, { method: 'POST', body: JSON.stringify(cleanFDA25(lot)) }, cookies, fetch);
            if (!res.ok) {
                const txt = await res.text();
                debugLog(`Error FDA25: ${res.status} - ${txt}`);
                throw new Error(`Error en FDA25: ${res.status} - ${txt}`);
            }
        }
    }
    debugLog(`saveNestedData finished successfully`);
}

export const GET: RequestHandler = async ({ url, cookies, fetch }) => {
    const companyId = url.searchParams.get('company_id') || cookies.get('active_company_id');
    const skip = url.searchParams.get('skip') || '0';
    const limit = url.searchParams.get('limit') || '50';
    const search = url.searchParams.get('search') || '';

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

    try {
        let apiUrl = `v1/a76/fda-catalog/?company_id=${companyId}&skip=${skip}&limit=${limit}`;
        if (search) apiUrl += `&search=${encodeURIComponent(search)}`;

        const response = await authenticatedFetch(apiUrl, { method: 'GET' }, cookies, fetch);
        if (!response.ok) return json({ error: 'Error al cargar registros FDA' }, { status: response.status });

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

export const POST: RequestHandler = async ({ request, cookies, fetch }) => {
    debugLog(`POST started`);
    const companyId = cookies.get('active_company_id');
    if (!companyId) return json({ error: 'Compañía no seleccionada' }, { status: 400 });

    try {
        const body = await request.json();
        const mainRecord = {
            fda_key: body.fda_key,
            description: body.description,
            fda_code: body.fda_code || null,
            requirements: body.requirements || null,
            manufacturer_number: body.manufacturer_number || null,
            country_of_production: body.country_of_production || null,
            storage_status: body.storage_status || null,
            warehouse_code: body.warehouse_code || null,
            call_atl: body.call_atl || null
        };

        debugLog(`Creating main record`);
        const res = await authenticatedFetch(`v1/a76/fda-catalog/?company_id=${companyId}`, { method: 'POST', body: JSON.stringify(mainRecord) }, cookies, fetch);
        const data = await res.json();
        if (!res.ok) {
            debugLog(`Error creating main record: ${res.status}`);
            return json({ error: data.detail || 'Error al crear FDA' }, { status: res.status });
        }

        await saveNestedData(data.id.toString(), companyId, body, cookies, fetch);
        debugLog(`POST finished successfully`);
        return json(data);
    } catch (error: any) {
        debugLog(`POST Crash: ${error.message}`);
        console.error('POST Error:', error);
        return json({ error: error.message || 'Error al procesar el guardado' }, { status: 500 });
    }
};

export const PUT: RequestHandler = async ({ request, url, cookies, fetch }) => {
    debugLog(`PUT started`);
    const id = url.searchParams.get('id');
    const companyId = url.searchParams.get('company_id') || cookies.get('active_company_id');

    debugLog(`PUT params: id=${id}, companyId=${companyId}`);
    if (!id || !companyId) return json({ error: 'ID o compañía no proporcionada' }, { status: 400 });

    try {
        const body = await request.json();
        const mainRecord = {
            fda_key: body.fda_key,
            description: body.description,
            fda_code: body.fda_code || null,
            requirements: body.requirements || null,
            manufacturer_number: body.manufacturer_number || null,
            country_of_production: body.country_of_production || null,
            storage_status: body.storage_status || null,
            warehouse_code: body.warehouse_code || null,
            call_atl: body.call_atl || null
        };

        debugLog(`Updating main record id=${id}`);
        const res = await authenticatedFetch(`v1/a76/fda-catalog/${id}?company_id=${companyId}`, { method: 'PUT', body: JSON.stringify(mainRecord) }, cookies, fetch);
        const data = await res.json();
        if (!res.ok) {
            debugLog(`Error updating main record: ${res.status}`);
            return json({ error: data.detail || 'Error al actualizar FDA' }, { status: res.status });
        }

        await saveNestedData(id, companyId, body, cookies, fetch);
        debugLog(`PUT finished successfully`);
        return json(data);
    } catch (error: any) {
        debugLog(`PUT Crash: ${error.message}`);
        console.error('PUT Error:', error);
        return json({ error: error.message || 'Error al procesar la actualización' }, { status: 500 });
    }
};

export const DELETE: RequestHandler = async ({ url, cookies, fetch }) => {
    const id = url.searchParams.get('id');
    const companyId = url.searchParams.get('company_id') || cookies.get('active_company_id');
    if (!id || !companyId) return json({ error: 'ID o compañía no proporcionada' }, { status: 400 });

    try {
        const res = await authenticatedFetch(`v1/a76/fda-catalog/${id}?company_id=${companyId}`, { method: 'DELETE' }, cookies, fetch);
        if (!res.ok) {
            const data = await res.json();
            return json({ error: data.detail || 'Error al eliminar FDA' }, { status: res.status });
        }
        return json({ success: true });
    } catch (error) {
        return json({ error: 'Error de conexión' }, { status: 500 });
    }
};
