import { type NextRequest, NextResponse } from "next/server";
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export async function PUT(
    request: NextRequest,
    { params }: { params: Promise<{ id: string }> }
) {
    try {
        const resolvedParams = await params;
        const id = parseInt(resolvedParams.id);
        const body = await request.json();
        const { responded, responseTemplate } = body;

        if (isNaN(id)) {
            return NextResponse.json(
                { error: 'Invalid contact ID' },
                { status: 400 }
            );
        }

        const contact = await prisma.contact.update({
            where: { id },
            data: {
                responded: responded !== undefined ? responded : undefined,
                responseTemplate: responseTemplate || undefined,
                updatedAt: new Date()
            }
        });

        return NextResponse.json({
            message: 'Contact updated successfully',
            contact
        });

    } catch (error) {
        console.error('Error updating contact:', error);
        return NextResponse.json(
            { error: 'Failed to update contact' },
            { status: 500 }
        );
    }
}

export async function DELETE(
    request: NextRequest,
    { params }: { params: Promise<{ id: string }> }
) {
    try {
        const resolvedParams = await params;
        const id = parseInt(resolvedParams.id);

        if (isNaN(id)) {
            return NextResponse.json(
                { error: 'Invalid contact ID' },
                { status: 400 }
            );
        }

        await prisma.contact.delete({
            where: { id }
        });

        return NextResponse.json({
            message: 'Contact deleted successfully'
        });

    } catch (error) {
        console.error('Error deleting contact:', error);
        return NextResponse.json(
            { error: 'Failed to delete contact' },
            { status: 500 }
        );
    }
}
