import type { APIRoute } from 'astro';
import { db } from '../../db/index';
import * as Indexing from '../../../scripts/pokemon-helper';

export const POST: APIRoute = async ({ request }) => {
    const { cards, skus, inventory, recreate } = await request.json().catch(() => ({} as any));

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

            try {
                if (!cards && !skus && !inventory) {
                    log('No collections selected.');
                    return;
                }

                if (recreate) {
                    if (cards) {
                        log('Recreating "cards" collection...');
                        await Indexing.createCardCollection(log);
                    }
                    if (skus) {
                        log('Recreating "skus" collection...');
                        await Indexing.createSkuCollection(log);
                    }
                    if (inventory) {
                        log('Recreating "inventories" collection...');
                        await Indexing.createInventoryCollection(log);
                    }
                }

                if (cards) {
                    log('Indexing "cards"...');
                    await Indexing.upsertCardCollection(db, log);
                }
                if (skus) {
                    log('Indexing "skus"...');
                    await Indexing.upsertSkuCollection(db, log);
                }
                if (inventory) {
                    log('Indexing "inventories"...');
                    await Indexing.upsertInventoryCollection(db, log);
                }

                log('Reindex complete.');
            } catch (e: any) {
                const cause = e?.cause;
                const causeMsg = cause?.message || (cause ? String(cause) : '');
                const causeDetail = cause?.detail ? ` | detail: ${cause.detail}` : '';
                const causeCode = cause?.code ? ` | code: ${cause.code}` : '';
                log(`Error: ${e?.message || String(e)}`);
                if (causeMsg) log(`Caused by: ${causeMsg}${causeCode}${causeDetail}`);
                console.error('Reindex 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',
        },
    });
};
