import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';

export async function POST(request: NextRequest) {
    try {
        const body = await request.json();
        const { slug, rating, comment } = body;

        if (!slug || !rating) {
            return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
        }

        // Find the QR code
        const qrCode = await db.qRCode.findUnique({
            where: { slug },
            select: { id: true },
        });

        if (!qrCode) {
            return NextResponse.json({ error: 'QR Code not found' }, { status: 404 });
        }

        // Log feedback as a scan with additional data
        // In a full implementation, you'd have a Feedback model
        // For now, we'll store it in QRScan with special markers
        await db.qRScan.create({
            data: {
                qrId: qrCode.id,
                ipHash: 'feedback',
                userAgent: `rating:${rating}|comment:${comment?.substring(0, 200) || ''}`,
                device: 'feedback',
                isUnique: true,
            },
        });

        return NextResponse.json({ success: true });
    } catch (error) {
        console.error('Error submitting feedback:', error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}
