import { NextRequest, NextResponse } from 'next/server';
import { history } from '@/lib/history';
import { WhiskClient } from '@/lib/whisk-client';
import { v4 as uuidv4 } from 'uuid';

export async function GET(req: NextRequest) {
    const { searchParams } = new URL(req.url);
    const category = searchParams.get('category') || undefined;

    const items = history.getAll(category);
    return NextResponse.json({ history: items });
}

export async function POST(req: NextRequest) {
    try {
        const formData = await req.formData();
        const file = formData.get('file') as File;
        const category = formData.get('category') as string || 'subject';
        const cookieString = formData.get('cookies') as string;

        if (!file) return NextResponse.json({ error: "No file provided" }, { status: 400 });

        const buffer = Buffer.from(await file.arrayBuffer());
        const base64 = buffer.toString('base64');
        const mimeType = file.type || 'image/png';

        // 1. Upload to Whisk (if cookies provided)
        let mediaId = undefined;
        if (cookieString) {
            const client = new WhiskClient(cookieString);
            mediaId = await client.uploadReferenceImage(base64, mimeType, category) || undefined;
        }

        // 2. Save to History
        // Ideally we save the file to `public/uploads` and return a URL.
        // For simplicity/speed in this MVP, we'll store the Data URI (Warning: Large JSON).
        // BETTER: Save file to disk.

        // Saving file to public/uploads
        // We need to assume the app runs where it can write to public.
        // In dev it works.

        /* 
        const fs = require('fs');
        const path = require('path');
        const uploadDir = path.join(process.cwd(), 'public', 'uploads');
        if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });
        
        const fileName = `${uuidv4()}.png`; // Normalize to PNG?
        const filePath = path.join(uploadDir, fileName);
        fs.writeFileSync(filePath, buffer);
        const url = `/uploads/${fileName}`;
        */

        // For now, let's use Data URI for immediate portability and less fs hassle in Next.js structure
        // (Next.js public folder isn't always writable in production builds easily without config)
        // But Data URI in JSON is bad.
        // Let's use Data URI for the response but assume successful upload implies we can use it.

        // Changing strategy: Use Data URI for history.json for now (simpler migration)
        const url = `data:${mimeType};base64,${base64}`;

        const newItem = history.add({
            id: uuidv4(),
            url,
            originalName: file.name,
            category,
            mediaId
        });

        return NextResponse.json(newItem);

    } catch (error: any) {
        console.error("Upload error:", error);
        return NextResponse.json({ error: error.message }, { status: 500 });
    }
}
