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');

export async function POST(req: Request) {
    try {
        const { id } = await req.json();
        if (!id) return NextResponse.json({ error: 'Missing ID' }, { status: 400 });

        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) {
            const now = Date.now();
            cache.prompts[promptIndex].useCount = (cache.prompts[promptIndex].useCount || 0) + 1;
            cache.prompts[promptIndex].lastUsedAt = now;

            await fs.writeFile(DATA_FILE, JSON.stringify(cache, null, 2));
        }

        return NextResponse.json({ success: true });
    } catch (error) {
        console.error('Failed to update usage:', error);
        return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
    }
}
