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

const prisma = new PrismaClient();

export async function GET(request: NextRequest) {
    try {
        const { searchParams } = new URL(request.url);
        const filter = searchParams.get('filter') || 'all';
        const limit = parseInt(searchParams.get('limit') || '50');
        const offset = parseInt(searchParams.get('offset') || '0');

        let whereClause = {};
        
        switch (filter) {
            case 'unread':
                whereClause = { responded: false };
                break;
            case 'responded':
                whereClause = { responded: true };
                break;
            default:
                whereClause = {};
        }

        const [contacts, total] = await Promise.all([
            prisma.contact.findMany({
                where: whereClause,
                orderBy: { createdAt: 'desc' },
                take: limit,
                skip: offset,
            }),
            prisma.contact.count({ where: whereClause })
        ]);

        return NextResponse.json({
            contacts,
            total,
            hasMore: offset + contacts.length < total
        });

    } 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. Returning empty result.');
            }
            return NextResponse.json({
                contacts: [],
                total: 0,
                hasMore: false
            });
        }
        
        if (process.env.NODE_ENV === 'development') {
            console.error('Error fetching contacts:', error);
        }
        return NextResponse.json(
            { error: 'Failed to fetch contacts' },
            { status: 500 }
        );
    }
}

export async function POST(request: NextRequest) {
    try {
        // Rate limiting for POST 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 body = await request.json();
        const { name, email, subject, message } = body;

        // Validate required fields
        if (!name || !email || !subject || !message) {
            return NextResponse.json(
                { error: 'All fields are required' },
                { status: 400 }
            );
        }

        // Validate email format
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            return NextResponse.json(
                { error: 'Invalid email format' },
                { status: 400 }
            );
        }

        const contact = await prisma.contact.create({
            data: {
                name,
                email,
                subject,
                message,
                responded: false
            }
        });

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

    } 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 creating contact:', error);
        }
        return NextResponse.json(
            { error: 'Failed to create contact' },
            { status: 500 }
        );
    }
}
