import pool from '../../../../lib/db/db';
import { NextRequest, NextResponse } from 'next/server';
import { FreeConsultationSchemaSoft as Schema } from '../../../../validations/freeconsultation';
import { ResultSetHeader, RowDataPacket } from 'mysql2';
import { sendFormEmail, FormType } from '../../../../lib/mailer';
import { hashData } from '../../../../lib/hashData';

// 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);
    }
}

// POST - Create new online consultant application
export async function POST(req: NextRequest) {
    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 req.json();
            originalBody = body;
            originalPayload = { ...body };
        } catch (parseError: any) {
            await logFormError(
                'online_consultant',
                parseError,
                null,
                'JSON_PARSE_ERROR'
            );
            
            return NextResponse.json({ 
                success: false, 
                message: 'Invalid JSON in request body' 
            }, { status: 400 });
        }
        
        // Validate with Zod schema
        let parsed;
        try {
            parsed = Schema.parse(body);
        } catch (validationError: any) {
            // Log Zod validation error
            await logFormError(
                'online_consultant',
                validationError,
                body,
                'VALIDATION_ERROR',
                { validationErrors: validationError.errors }
            );
            
            // Format Zod errors for frontend display
            const formattedErrors = validationError.errors.map((error: any) => ({
                field: error.path.join('.'),
                message: error.message
            }));
            
            return NextResponse.json({ 
                success: false, 
                message: 'Validation failed. Please check your input.',
                errors: formattedErrors
            }, { status: 400 });
        }

        const { name, email, phone_number, phonecode, last_education, interested_country, apply_for, office_to_visit } = parsed;

        const phonewithcode = `${phonecode}${phone_number}`;

        // Get country name from phone code
        let getCountryName;
        try {
            const [countryResult] = await connection.query<RowDataPacket[]>(
                "SELECT name FROM countries_with_phone WHERE phonecode = ?", 
                [phonecode]
            );
            getCountryName = countryResult;

            if (getCountryName.length === 0) {
                await logFormError(
                    'online_consultant',
                    new Error('Invalid country code'),
                    parsed,
                    'INVALID_COUNTRY_CODE',
                    { phonecode, phone_number }
                );
                
                return NextResponse.json(
                    {
                        success: false,
                        message: 'Invalid country code'
                    },
                    { status: 400 }
                );
            }
        } catch (countryError: any) {
            await logFormError(
                'online_consultant',
                countryError,
                parsed,
                'DATABASE_ERROR',
                { query: 'SELECT country by phonecode', phonecode }
            );
            throw countryError;
        }

        // Insert into database
        let insertResult;
        try {
            const [newApplication] = await connection.query<ResultSetHeader>(
                `INSERT INTO online_consultants (
                    application_type, 
                    student_name, 
                    student_email, 
                    student_phone_number, 
                    student_last_education, 
                    student_apply_for, 
                    interested_country, 
                    office_to_visit, 
                    student_country,
                    student_city,
                    choosable_status, 
                    created_at, 
                    updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Pending', NOW(), NOW())`,
                [
                    '2', // application_type
                    name, // student_name
                    email || '', // student_email
                    phonewithcode, // student_phone_number
                    last_education, // student_last_education
                    apply_for, // student_apply_for
                    interested_country, // interested_country
                    office_to_visit, // office_to_visit
                    getCountryName[0].name, // student_country
                    office_to_visit // student_city
                ]
            );
            insertResult = newApplication;

            if (insertResult.affectedRows === 0) {
                await logFormError(
                    'online_consultant',
                    new Error('Database insertion failed - no rows affected'),
                    parsed,
                    'DB_INSERT_FAILED'
                );
                
                await connection.rollback();
                return NextResponse.json({ 
                    success: false, 
                    message: 'Failed to create application' 
                }, { status: 500 });
            }
        } catch (dbError: any) {
            await logFormError(
                'online_consultant',
                dbError,
                { ...parsed, stage: 'database_insert' },
                'DATABASE_ERROR',
                { table: 'online_consultants', query: 'INSERT' }
            );
            throw dbError;
        }

        // Prepare payload for CRM
        const crmPayload = {
            application_type: "2",
            student_name: name,
            student_email: email || '',
            student_phone_number: phonewithcode,
            student_country: getCountryName[0].name,
            student_city: office_to_visit,
            student_last_education: last_education,
            student_apply_for: apply_for,
            interested_country: interested_country,
            office_to_visit: office_to_visit,
            choosable_status: "Pending"
        };

        // Send to CRM
        let crmResponse;
        try {
            crmResponse = await fetch(
                "https://crm-universitiespage.com/reactapis/api/website_online_consultation_crm/store?location=lahore",
                {
                    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(
                'online_consultant',
                crmError,
                { originalPayload: parsed, crmPayload },
                'CRM_API_ERROR',
                { 
                    responseStatus: crmResponse?.status,
                    endpoint: 'website_online_consultation_crm/store',
                    location: 'lahore'
                }
            );
            
            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
        try {
            const [emailHash, phoneHash] = await Promise.all([
                email ? hashData(email) : Promise.resolve(''),
                hashData(phonewithcode)
            ]);

            const event = {
                event_name: "Apply Online",
                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) {
                // Log Facebook error but don't fail the request
                await logFormError(
                    'online_consultant',
                    new Error(`Facebook Pixel failed: ${fbResponse.status}`),
                    { fbPayload },
                    'FACEBOOK_PIXEL_ERROR',
                    { responseStatus: fbResponse.status }
                );
                console.error("Facebook Pixel event failed");
            }
        } catch (fbError: any) {
            await logFormError(
                'online_consultant',
                fbError,
                { error: 'Facebook Pixel processing error' },
                'FACEBOOK_PIXEL_ERROR'
            );
            console.error("Facebook Pixel Error:", fbError);
        }

        await connection.commit();

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

        return NextResponse.json({ 
            success: true, 
            message: 'Application created successfully' 
        }, { status: 201 });

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

        // Log any unhandled error
        await logFormError(
            'online_consultant',
            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("POST online_consultants error:", error);
        
        // Handle specific database errors
        if (error.code === 'ER_DUP_ENTRY') {
            return NextResponse.json({ 
                success: false, 
                message: 'Duplicate entry. You may have already applied.' 
            }, { status: 409 });
        }
        
        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: 'Internal server error', 
            error: process.env.NODE_ENV === 'development' ? error.message : null 
        }, { status: 500 });
    } finally {
        connection.release();
    }
}