import { NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';

export function createApiHandler(jsonFileName: string, idPrefix: string) {
    const dataPath = path.join(process.cwd(), 'src/data', jsonFileName);

    function getData() {
        if (!fs.existsSync(dataPath)) return [];
        return JSON.parse(fs.readFileSync(dataPath, 'utf8'));
    }

    function saveData(data: any) {
        fs.writeFileSync(dataPath, JSON.stringify(data, null, 2));
    }

    return {
        async GET() {
            try {
                return NextResponse.json(getData());
            } catch (e) {
                return NextResponse.json({ error: 'Failed' }, { status: 500 });
            }
        },
        async POST(request: Request) {
            try {
                const body = await request.json();
                const data = getData();
                const newItem = { ...body, id: idPrefix + '_' + Date.now().toString() };
                data.push(newItem);
                saveData(data);
                return NextResponse.json(newItem);
            } catch (e) {
                return NextResponse.json({ error: 'Failed' }, { status: 500 });
            }
        },
        async PUT(request: Request) {
            try {
                const body = await request.json();
                const { id, ...updates } = body;
                let data = getData();
                const index = data.findIndex((p: any) => p.id === id);
                if (index === -1) return NextResponse.json({ error: 'Not found' }, { status: 404 });
                data[index] = { ...data[index], ...updates };
                saveData(data);
                return NextResponse.json(data[index]);
            } catch (e) {
                return NextResponse.json({ error: 'Failed' }, { status: 500 });
            }
        },
        async DELETE(request: Request) {
            try {
                const { searchParams } = new URL(request.url);
                const id = searchParams.get('id');
                if (!id) return NextResponse.json({ error: 'ID required' }, { status: 400 });
                let data = getData();
                const filteredData = data.filter((p: any) => p.id !== id);
                saveData(filteredData);
                return NextResponse.json({ success: true });
            } catch (e) {
                return NextResponse.json({ error: 'Failed' }, { status: 500 });
            }
        },
        async PATCH(request: Request) {
            try {
                const body = await request.json();
                if (!Array.isArray(body)) return NextResponse.json({ error: 'Array required' }, { status: 400 });
                saveData(body);
                return NextResponse.json({ success: true });
            } catch (e) {
                return NextResponse.json({ error: 'Failed' }, { status: 500 });
            }
        }
    };
}
