import { NextRequest, NextResponse } from 'next/server';
import mysql from 'mysql2/promise';

export async function POST(request: NextRequest) {
  let connection: mysql.Connection | null = null;

  // Authorization check
  const comingHeaders = request.headers.get("authorization");
  if (comingHeaders !== process.env.APP_API_KEY) {
    return NextResponse.json(
      { success: false, message: 'Unauthorized Access' },
      { status: 401 }
    );
  }

  try {
    const body = await request.json();

    // Validate required fields - accept both phone and phoneNumber
    const phoneNumber = body.phoneNumber || body.phone;
    if (!body.name || !body.email || !phoneNumber) {
      return NextResponse.json(
        { success: false, message: 'Name, email, and phone number are required' },
        { status: 400 }
      );
    }

    // Create DB connection
    connection = await mysql.createConnection({
      host: process.env.DB_HOST,
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_NAME,
      port: parseInt(process.env.DB_PORT || '3306')
    });

    // Start transaction
    await connection.beginTransaction();

    // Insert into ai_scholarship_predictors table
    const query = `
      INSERT INTO ai_scholarship_predictors (
        name, email, phoneNumber, age, nationality,
        educationLevel, cgpa, fieldOfStudy, languageScore, languageProof,
        researchExperience, publications, awards, preferredCountries,
        degreeLevel, fundingPriority, searchType, matchedCount, analysisScore,
        profileProgress, profileData, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
    `;

    const values = [
      body.name,
      body.email,
      phoneNumber,
      body.age || null,
      body.nationality || '',
      body.educationLevel || '',
      parseFloat(body.cgpa?.toString() || '0'),
      body.fieldOfStudy || '',
      parseFloat(body.languageScore?.toString() || '0'),
      body.languageProof || '',
      body.researchExperience || '',
      body.publications || '',
      body.awards || '',
      JSON.stringify(body.preferredCountries || []),
      body.degreeLevel || '',
      body.fundingPriority || '',
      body.searchType || 'scholarship_match',
      body.matchedCount || 0,
      parseFloat(body.analysisScore?.toString() || '0'),
      body.profileProgress || 0,
      JSON.stringify(body.profileData || {})
    ];

    const [result] = await connection.execute(query, values);
    const insertedId = (result as any).insertId;

    console.log('✅ Database insert successful, ID:', insertedId);

    // Prepare payload for CRM API (matching working pattern)
    const crmPayload = {
      name: body.name,
      email: body.email,
      phoneNumber: phoneNumber,
      age: body.age ? parseInt(body.age) : null,
      nationality: body.nationality || '',
      currentCountry: body.currentCountry || '',
      educationLevel: body.educationLevel || '',
      cgpa: parseFloat(body.cgpa?.toString() || '0'),
      fieldOfStudy: body.fieldOfStudy || '',
      languageScore: parseFloat(body.languageScore?.toString() || '0'),
      languageProof: body.languageProof || '',
      researchExperience: body.researchExperience || '',
      publications: body.publications || '',
      awards: body.awards || '',
      preferredCountries: body.preferredCountries || [],
      degreeLevel: body.degreeLevel || '',
      fundingPriority: body.fundingPriority || '',
      searchType: body.searchType || 'scholarship_match',
      matchedCount: body.matchedCount || 0,
      analysisScore: parseFloat(body.analysisScore?.toString() || '0'),
      profileProgress: body.profileProgress || 0,
      profileData: body.profileData || {},
      lead_id: insertedId,
      source: 'ai_scholarship_predictor',
      lead_type: 'mobile',
      timestamp: new Date().toISOString()
    };

    console.log('📤 Sending to CRM:', JSON.stringify(crmPayload, null, 2));
    console.log('🔑 CRM API Key present:', !!process.env.CRM_API_KEY);

    // Hit CRM API (matching working pattern - NO Bearer prefix)
    const crmResponse = await fetch("https://crm-universitiespage.com/reactapis/api/predictors/scholarship", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json',
        'Authorization': process.env.CRM_API_KEY || '',  // No "Bearer " prefix
      },
      body: JSON.stringify(crmPayload)
    });

    // Get response as text first to debug
    const responseText = await crmResponse.text();
    console.log('📥 CRM Response Status:', crmResponse.status);
    console.log('📥 CRM Response Body:', responseText);

    let crmData;
    try {
      crmData = JSON.parse(responseText);
    } catch (parseError) {
      console.error('Failed to parse CRM response:', parseError);
      crmData = { raw_response: responseText };
    }

    // Check for success (matching working pattern)
    const isSuccess = crmData?.status_code === 200 || crmData?.success === true || crmResponse.ok;

    if (!isSuccess) {
      console.error('CRM API error:', crmData);
      await connection.rollback();
      await connection.end();
      
      // Return detailed error message
      let errorMessage = 'Failed to send lead to CRM. Transaction rolled back.';
      if (crmData?.message) {
        errorMessage += ` CRM says: ${crmData.message}`;
      }
      if (crmData?.error) {
        errorMessage += ` Error: ${JSON.stringify(crmData.error)}`;
      }
      
      return NextResponse.json(
        {
          success: false,
          message: errorMessage,
          crmResponse: crmData,
          crmStatus: crmResponse.status
        },
        { status: 500 }
      );
    }

    // Commit transaction
    await connection.commit();
    await connection.end();

    console.log('✅ Lead saved to both databases successfully');

    return NextResponse.json({
      success: true,
      message: 'Lead saved and sent to CRM successfully',
      id: insertedId,
      crm_response: crmData
    }, { status: 201 });

  } catch (error: any) {
    console.error('❌ Error storing scholarship lead:', error);
    
    if (connection) {
      try {
        await connection.rollback();
        await connection.end();
      } catch (rollbackError) {
        console.error('Error during rollback:', rollbackError);
      }
    }
    
    return NextResponse.json(
      { 
        success: false, 
        message: error.message || 'Failed to store lead',
        error: process.env.NODE_ENV === 'development' ? error.stack : undefined
      },
      { status: 500 }
    );
  }
}