import { NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { Prisma } from '@prisma/client';

interface LeadInput {
    email: string;
    source?: string;
    reprintCost?: number;
    updatesPerYear?: number;
    annualSavings?: number;
}

export async function POST(request: Request) {
    try {
        const body: LeadInput = await request.json();
        const { email, source, reprintCost, updatesPerYear, annualSavings } = body;

        if (!email || !email.includes('@')) {
            return NextResponse.json(
                { error: 'Valid email is required' },
                { status: 400 }
            );
        }

        // Use typed db client - keeping (db as any) temporarily if types are missing locally, 
        // but cleaner code should use db.lead directly. 
        // We will trust the user to run `npm run build` which runs `prisma generate`.
        const lead = await db.lead.create({
            data: {
                email: email.toLowerCase().trim(),
                source: source || 'reprint-calculator',
                reprintCost: reprintCost ? Number(reprintCost) : null,
                updatesPerYear: updatesPerYear ? Number(updatesPerYear) : null,
                annualSavings: annualSavings ? Number(annualSavings) : null,
            },
        });

        return NextResponse.json({ success: true, id: lead.id });
    } catch (error) {
        console.error('Error saving lead:', error);

        if (error instanceof Prisma.PrismaClientKnownRequestError) {
            if (error.code === 'P2021') {
                console.error('CRITICAL: Table "Lead" does not exist in the database. Run "npx prisma migrate deploy" to fix this.');
                return NextResponse.json(
                    {
                        error: 'Database configuration error',
                        details: 'Missing database table. Please run migrations.'
                    },
                    { status: 500 }
                );
            }
        }

        // Return the actual error message for debugging purposes
        return NextResponse.json(
            {
                error: 'Failed to save lead',
                details: error instanceof Error ? error.message : String(error)
            },
            { status: 500 }
        );
    }
}

export async function GET() {
    try {
        const [leads, total] = await Promise.all([
            db.lead.findMany({
                orderBy: { createdAt: 'desc' },
                take: 10,
            }),
            (db as any).lead.count(),
        ]);

        return NextResponse.json({
            total,
            recent: leads.map((lead: {
                id: string;
                email: string;
                source: string;
                reprintCost: number | null;
                updatesPerYear: number | null;
                annualSavings: number | null;
                createdAt: Date;
            }) => ({
                id: lead.id,
                email: lead.email,
                source: lead.source,
                reprintCost: lead.reprintCost,
                updatesPerYear: lead.updatesPerYear,
                annualSavings: lead.annualSavings,
                createdAt: lead.createdAt.toISOString(),
            })),
        });
    } catch (error) {
        console.error('Error fetching leads:', error);
        return NextResponse.json(
            { error: 'Failed to fetch leads' },
            { status: 500 }
        );
    }
}
