import type { APIRoute } from 'astro';
import { runImport } from '../../../scripts/preload-tcgplayer';

export const POST: APIRoute = async ({ request }) => {
    const { setName } = await request.json().catch(() => ({} as any));
    const trimmed = typeof setName === 'string' ? setName.trim() : '';

    const encoder = new TextEncoder();
    const stream = new ReadableStream({
        async start(controller) {
            const log = (msg: string) => {
                controller.enqueue(encoder.encode(msg + '\n'));
            };

            try {
                if (!trimmed) {
                    log('Set name is required.');
                    return;
                }

                log(`Starting TCGPlayer import for set: "${trimmed}"`);
                await runImport({ sets: [trimmed], log });
                log('TCGPlayer import complete.');
            } catch (e: any) {
                const cause = e?.cause;
                const causeMsg = cause?.message || (cause ? String(cause) : '');
                log(`Error: ${e?.message || String(e)}`);
                if (causeMsg) log(`Caused by: ${causeMsg}`);
                console.error('TCGPlayer import error:', e);
            } finally {
                controller.close();
            }
        },
    });

    return new Response(stream, {
        headers: {
            'Content-Type': 'text/plain; charset=utf-8',
            'Cache-Control': 'no-cache, no-transform',
            'X-Accel-Buffering': 'no',
        },
    });
};
