import { NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';
import { PromptCache } from '@/lib/types';

const DATA_FILE = path.join(process.cwd(), 'data', 'prompts.json');
const PUBLIC_DIR = path.join(process.cwd(), 'public');

export async function POST(req: Request) {
    try {
        const { id, imageBase64 } = await req.json();

        if (!id || !imageBase64) {
            return NextResponse.json({ error: 'Missing id or imageBase64' }, { status: 400 });
        }

        // 1. Save Image
        // Remove data header if present
        const base64Data = imageBase64.replace(/^data:image\/\w+;base64,/, "");
        const buffer = Buffer.from(base64Data, 'base64');
        const filename = `prompt_${id}_${Date.now()}.png`;
        const relativePath = `/prompts/${filename}`;
        const fullPath = path.join(PUBLIC_DIR, 'prompts', filename);

        await fs.writeFile(fullPath, buffer);

        // 2. Update JSON
        const fileContent = await fs.readFile(DATA_FILE, 'utf-8');
        const cache: PromptCache = JSON.parse(fileContent);

        const promptIndex = cache.prompts.findIndex(p => p.id === id);
        if (promptIndex === -1) {
            return NextResponse.json({ error: 'Prompt not found' }, { status: 404 });
        }

        // Add to images array
        if (!cache.prompts[promptIndex].images) {
            cache.prompts[promptIndex].images = [];
        }
        cache.prompts[promptIndex].images.unshift(relativePath);

        await fs.writeFile(DATA_FILE, JSON.stringify(cache, null, 2), 'utf-8');

        return NextResponse.json({ success: true, url: relativePath });

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