import pool from '../../../../lib/db/db';
import { NextRequest, NextResponse } from 'next/server';
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 Contact Message =================
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(
                'contact_us',
                parseError,
                null,
                'JSON_PARSE_ERROR'
            );
            
            return NextResponse.json(
                { success: false, message: 'Invalid JSON in request body' },
                { status: 400 }
            );
        }

        const { office_location, user_name, user_email, phone_number, message } = body;

        // Validate required fields
        const missingFields = [];
        if (!office_location) missingFields.push('office_location');
        if (!user_name) missingFields.push('user_name');
        if (!user_email) missingFields.push('user_email');
        if (!phone_number) missingFields.push('phone_number');
        if (!message) missingFields.push('message');

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

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

        // Validate phone number (basic validation)
        if (phone_number && !/^[\d\s\+\(\)\-]{8,20}$/.test(phone_number)) {
            await logFormError(
                'contact_us',
                new Error(`Invalid phone number format: ${phone_number}`),
                body,
                'INVALID_PHONE_FORMAT',
                { phone: phone_number }
            );
            
            return NextResponse.json(
                { success: false, message: 'Invalid phone number format' },
                { status: 400 }
            );
        }

        // Insert into database with transaction connection
        let insertResult;
        try {
            const [result] = await connection.query<ResultSetHeader>(
                `INSERT INTO contact_us_messages 
                    (office_location, user_name, user_email, phone_number, message) 
                VALUES (?, ?, ?, ?, ?)`,
                [office_location, user_name, user_email, phone_number, message]
            );
            insertResult = result;

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

        // Prepare CRM payload
        const crmPayload = {
            office_location,
            user_name,
            user_email,
            phone_number,
            message
        };

        // Send to CRM
        let crmResponse;
        try {
            crmResponse = await fetch(
                "https://crm-universitiespage.com/reactapis/api/website_contact_us_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(
                'contact_us',
                crmError,
                { originalPayload: body, crmPayload },
                'CRM_API_ERROR',
                { 
                    responseStatus: crmResponse?.status,
                    endpoint: 'website_contact_us_crm/store',
                    email: user_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(user_email),
                hashData(phone_number)
            ]);

            const event = {
                event_name: "Contact Us",
                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(
                    'contact_us',
                    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(
                'contact_us',
                fbError,
                { error: 'Facebook Pixel processing error' },
                'FACEBOOK_PIXEL_ERROR'
            );
            console.error("Facebook Pixel Error:", fbError);
        }

        // Commit transaction
        await connection.commit();

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

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

        return NextResponse.json(
            { 
                success: true, 
                message: responseMessage,
                ...(!fbSuccess && { warning: 'Facebook tracking failed' })
            },
            { status: 201 }
        );
        
    } catch (error: any) {
        await connection.rollback();

        // Log any unhandled error
        await logFormError(
            'contact_us',
            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 /contactUs error:", error);
        
        // Handle specific database errors
        if (error.code === 'ER_DUP_ENTRY') {
            return NextResponse.json(
                { success: false, message: 'Duplicate entry. This message 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: 'Internal server error' },
            { status: 500 }
        );
    } finally {
        connection.release();
    }
}