import { type NextRequest, NextResponse } from "next/server";
import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';
import { checkRateLimit, getRateLimitHeaders, requireSessionAuth } from '@/lib/auth';
import { prisma } from "@/lib/prisma";

export async function PUT(
    request: NextRequest,
    { params }: { params: Promise<{ id: string }> }
) {
    try {
        // Rate limiting for PUT requests
        const ip = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown';
        if (!checkRateLimit(ip, 5, 60000)) { // 5 requests per minute
            return new NextResponse(
                JSON.stringify({ error: 'Rate limit exceeded' }), 
                { 
                    status: 429, 
                    headers: { 
                        'Content-Type': 'application/json',
                        ...getRateLimitHeaders(ip, 5, 60000)
                    } 
                }
            );
        }

        const isAdminRequest = request.headers.get('x-admin-request') === 'true';
        if (!isAdminRequest) return NextResponse.json({ error: 'Admin access required' }, { status: 403 });
        const authError = requireSessionAuth(request);
        if (authError) return authError;

        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) {
        // Handle missing database table gracefully
        if (error instanceof PrismaClientKnownRequestError && error.code === 'P2021') {
            if (process.env.NODE_ENV === 'development') {
                console.warn('Contact table does not exist.');
            }
            return NextResponse.json(
                { error: 'Database table not found. Please run migrations.' },
                { status: 503 }
            );
        }
        
        if (process.env.NODE_ENV === 'development') {
            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 {
        // Rate limiting for DELETE requests
        const ip = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown';
        if (!checkRateLimit(ip, 3, 60000)) { // 3 requests per minute for DELETE (more restrictive)
            return new NextResponse(
                JSON.stringify({ error: 'Rate limit exceeded' }), 
                { 
                    status: 429, 
                    headers: { 
                        'Content-Type': 'application/json',
                        ...getRateLimitHeaders(ip, 3, 60000)
                    } 
                }
            );
        }

        const isAdminRequest = request.headers.get('x-admin-request') === 'true';
        if (!isAdminRequest) return NextResponse.json({ error: 'Admin access required' }, { status: 403 });
        const authError = requireSessionAuth(request);
        if (authError) return authError;

        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) {
        // Handle missing database table gracefully
        if (error instanceof PrismaClientKnownRequestError && error.code === 'P2021') {
            if (process.env.NODE_ENV === 'development') {
                console.warn('Contact table does not exist.');
            }
            return NextResponse.json(
                { error: 'Database table not found. Please run migrations.' },
                { status: 503 }
            );
        }
        
        if (process.env.NODE_ENV === 'development') {
            console.error('Error deleting contact:', error);
        }
        return NextResponse.json(
            { error: 'Failed to delete contact' },
            { status: 500 }
        );
    }
}
