import pool from '../../../../lib/db/db';
import { NextResponse } from 'next/server';
import { sendFormEmail, FormType } from '../../../../lib/mailer';
import { hashData } from '../../../../lib/hashData';
import { ResultSetHeader, RowDataPacket } from 'mysql2';

// Helper function to log errors
async function logFormError(
    formType: string, 
    error: any, 
    payload?: any,
    errorCode?: string,
    additionalInfo?: any
) {
    try {
        const connection = await pool.getConnection();
        
        await connection.query(
            `INSERT INTO form_submission_errors 
             (form_type, error_message, error_code, payload, error_stack, additional_info) 
             VALUES (?, ?, ?, ?, ?, ?)`,
            [
                formType,
                error?.message || 'Unknown error',
                errorCode || error?.code || null,
                payload ? JSON.stringify(payload) : null,
                error?.stack?.substring(0, 1000) || null,
                additionalInfo ? JSON.stringify(additionalInfo) : null
            ]
        );
        
        connection.release();
    } catch (logError) {
        console.error('Failed to log error:', logError);
    }
}

export async function POST(request: Request) {
    const connection = await pool.getConnection();
    let originalPayload: any = null;
    let originalBody: any = null;

    try {
        await connection.beginTransaction();

        const accessToken = process.env.FACEBOOK_ACCESS_CODE;
        const pixelId = process.env.FACEBOOK_PIXEL_ID;

        // Parse request body
        let body;
        try {
            body = await request.json();
            originalBody = body;
            originalPayload = { ...body };
        } catch (parseError: any) {
            await logFormError(
                'minhaj_university',
                parseError,
                null,
                'JSON_PARSE_ERROR'
            );
            
            return NextResponse.json(
                { success: false, message: 'Invalid JSON in request body' },
                { status: 400 }
            );
        }

        const {
            full_name,
            roll_number,
            department,
            email,
            last_education,
            country,
            city,
            interested_country,
            apply_for,
            whatsapp_number,
        } = body;

        // Validate required fields
        const missingFields = [];
        if (!full_name) missingFields.push('full_name');
        if (!email) missingFields.push('email');
        if (!whatsapp_number) missingFields.push('whatsapp_number');

        if (missingFields.length > 0) {
            await logFormError(
                'minhaj_university',
                new Error(`Missing required fields: ${missingFields.join(', ')}`),
                body,
                'MISSING_REQUIRED_FIELDS',
                { missingFields }
            );
            
            return NextResponse.json(
                { 
                    success: false, 
                    message: `Missing required fields: ${missingFields.join(', ')}` 
                },
                { status: 400 }
            );
        }

        // Validate email format
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (email && !emailRegex.test(email)) {
            await logFormError(
                'minhaj_university',
                new Error(`Invalid email format: ${email}`),
                body,
                'INVALID_EMAIL_FORMAT',
                { email }
            );
            
            return NextResponse.json(
                { success: false, message: 'Invalid email format' },
                { status: 400 }
            );
        }

        // Insert into database
        let insertResult;
        try {
            const [result] = await connection.execute<ResultSetHeader>(
                `INSERT INTO minhaj_university_leads 
                 (full_name, roll_number, department, email, last_education, country, city, interested_country, apply_for, whatsapp_number, created_at) 
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())`,
                [full_name, roll_number, department, email, last_education, country, city, interested_country, apply_for, whatsapp_number]
            );
            insertResult = result;

            if (insertResult.affectedRows === 0) {
                await logFormError(
                    'minhaj_university',
                    new Error('Database insertion failed - no rows affected'),
                    body,
                    'DB_INSERT_FAILED'
                );
                
                await connection.rollback();
                return NextResponse.json(
                    { success: false, message: 'Failed to create lead' },
                    { status: 500 }
                );
            }
        } catch (dbError: any) {
            await logFormError(
                'minhaj_university',
                dbError,
                body,
                'DATABASE_ERROR',
                { 
                    table: 'minhaj_university_leads',
                    query: 'INSERT',
                    sqlCode: dbError.code,
                    sqlMessage: dbError.sqlMessage
                }
            );
            throw dbError;
        }

        // Prepare CRM payload
        const crmPayload = {
            full_name,
            roll_number,
            department,
            email,
            last_education,
            country,
            city,
            interested_country,
            apply_for,
            whatsapp_number,
        };

        // Send to CRM
        let crmResponse;
        try {
            crmResponse = await fetch(
                "https://crm-universitiespage.com/reactapis/api/website_minhaj_leads_crm/store",
                {
                    method: "POST",
                    body: JSON.stringify(crmPayload),
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `${process.env.CRM_API_KEY}`,
                    },
                }
            );

            if (!crmResponse.ok) {
                throw new Error(`CRM API responded with status: ${crmResponse.status}`);
            }

            const data = await crmResponse.json();

            if (data?.status_code !== 200) {
                throw new Error(`CRM API returned status_code: ${data?.status_code}`);
            }
        } catch (crmError: any) {
            // Log CRM error
            await logFormError(
                'minhaj_university',
                crmError,
                { originalPayload: body, crmPayload },
                'CRM_API_ERROR',
                { 
                    responseStatus: crmResponse?.status,
                    endpoint: 'website_minhaj_leads_crm/store',
                    email: email
                }
            );
            
            await connection.rollback();
            console.error('CRM API Error:', crmError);
            
            return NextResponse.json(
                {
                    message: "Failed to submit your form. Please try again later.",
                    success: false
                },
                { status: 502 }
            );
        }

        // Facebook Pixel Event
        let fbSuccess = true;
        try {
            const [emailHash, phoneHash] = await Promise.all([
                hashData(email),
                hashData(whatsapp_number)
            ]);

            const event = {
                event_name: "Minhaj University",
                event_time: Math.floor(Date.now() / 1000),
                user_data: {
                    email: emailHash,
                    ph: phoneHash,
                },
            };

            const fbPayload = { data: [event] };

            const fbResponse = await fetch(
                `https://graph.facebook.com/v14.0/${pixelId}/events?access_token=${accessToken}`,
                {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify(fbPayload),
                }
            );

            if (!fbResponse.ok) {
                fbSuccess = false;
                // Log Facebook error but don't fail the request
                await logFormError(
                    'minhaj_university',
                    new Error(`Facebook Pixel failed: ${fbResponse.status}`),
                    { fbPayload },
                    'FACEBOOK_PIXEL_ERROR',
                    { 
                        responseStatus: fbResponse.status,
                        responseText: await fbResponse.text()
                    }
                );
                console.error("Facebook Pixel event failed");
            }
        } catch (fbError: any) {
            fbSuccess = false;
            await logFormError(
                'minhaj_university',
                fbError,
                { error: 'Facebook Pixel processing error' },
                'FACEBOOK_PIXEL_ERROR'
            );
            console.error("Facebook Pixel Error:", fbError);
        }

        // Only commit if database and CRM succeeded
        await connection.commit();

        // Send confirmation email
        try {
            await sendFormEmail(FormType.MINHAJ_UNIVERSITY, {
                email: email
            });
        } catch (emailError: any) {
            // Log email error but don't fail the request
            await logFormError(
                'minhaj_university',
                emailError,
                { email },
                'EMAIL_SEND_ERROR',
                { formType: FormType.MINHAJ_UNIVERSITY }
            );
            console.error('Email send failed:', emailError);
        }

        // Return response with warning if Facebook Pixel failed
        const responseMessage = fbSuccess 
            ? 'Lead created successfully'
            : 'Lead created successfully but tracking event failed';

        return NextResponse.json({
            success: true,
            message: responseMessage,
            data: {
                id: insertResult.insertId,
                full_name,
                roll_number,
                department,
                email,
                last_education,
                country,
                city,
                interested_country,
                apply_for,
                whatsapp_number
            }
        }, { status: 201 });

    } catch (error: any) {
        await connection.rollback();

        // Log any unhandled error
        await logFormError(
            'minhaj_university',
            error,
            originalPayload,
            error.code?.startsWith('ER_') ? 'DATABASE_ERROR' : 'UNHANDLED_ERROR',
            { 
                stage: 'general_catch_block',
                sqlCode: error.code,
                sqlErrno: error.errno,
                sqlMessage: error.sqlMessage
            }
        );

        console.error('Error creating lead:', error);
        
        // Handle specific database errors
        if (error.code === 'ER_DUP_ENTRY') {
            return NextResponse.json(
                { success: false, message: 'Duplicate entry. This lead may already exist.' },
                { status: 409 }
            );
        }
        
        if (error.code === 'ER_BAD_NULL_ERROR') {
            return NextResponse.json(
                { success: false, message: 'Required field cannot be null' },
                { status: 400 }
            );
        }
        
        if (error.code?.startsWith('ER_')) {
            return NextResponse.json(
                { success: false, message: 'Database error occurred. Please try again later.' },
                { status: 500 }
            );
        }
        
        return NextResponse.json(
            { success: false, message: 'Failed to create lead', error: error.message },
            { status: 500 }
        );
    } finally {
        connection.release();
    }
}