import { NextRequest, NextResponse } from "next/server";
import pool from '../../../../../lib/db/db';
import { RowDataPacket } from 'mysql2';

// CRM API endpoint
const CRM_API_URL = 'https://crm-universitiespage.com/reactapis/api/website_study_plan/store';

export async function POST(request: NextRequest) {
  const commingHeaders = request.headers.get("authorization");

  if (commingHeaders !== process.env.APP_API_KEY) {
    return NextResponse.json(
      { success: false, message: 'Unauthorized Access' },
      { status: 401 }
    );
  }
  
  const connection = await pool.getConnection();
  
  try {
    const body = await request.json();
    const { planId } = body;

    console.log('📥 Received planId:', planId);

    if (!planId) {
      return new Response(
        JSON.stringify({ 
          success: false,
          error: 'Missing planId' 
        }),
        { 
          status: 400, 
          headers: { 'Content-Type': 'application/json' }
        }
      );
    }

    // Get complete study plan data
    const [planData] = await connection.execute<RowDataPacket[]>(
      `SELECT 
        full_name, email, phone, last_education, education_level,
        cgpa, study_gap, target_country, target_university,
        target_course, word_count, response_style, study_plan,
        english_test, english_score, gap_justification, nationality
       FROM study_plans WHERE id = ?`,
      [planId]
    );

    console.log('📥 Retrieved plan data:', planData[0]);

    if (planData.length === 0) {
      return new Response(
        JSON.stringify({ 
          success: false,
          error: 'Study plan data not found' 
        }),
        { 
          status: 404, 
          headers: { 'Content-Type': 'application/json' }
        }
      );
    }

    const plan = planData[0];

    // Prepare CRM payload - matching your CRM API expectations
    const crmPayload = {
      fullName: plan.full_name,
      email: plan.email,
      phone: plan.phone,
      lastEducation: plan.last_education,
      educationLevel: plan.education_level,
      cgpa: plan.cgpa,
      studyGap: plan.study_gap,
      country: plan.target_country,
      university: plan.target_university,
      course: plan.target_course,
      wordCount: plan.word_count,
      responseStyle: plan.response_style,
      study_plan: plan.study_plan,
      englishTest: plan.english_test,
      englishScore: plan.english_score,
      gapJustification: plan.gap_justification,
      lead_type: 'mobile',
      nationality: plan.nationality
    };

    console.log('📤 Sending to CRM:', JSON.stringify(crmPayload, null, 2));

    // Send to CRM API
    const crmApiResponse = await fetch(CRM_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': process.env.CRM_API_KEY || '',
      },
      body: JSON.stringify(crmPayload),
    });

    console.log('📥 CRM Response Status:', crmApiResponse.status);
    
    // Get the response text
    const responseText = await crmApiResponse.text();
    console.log('📥 CRM Raw Response:', responseText);

    let crmData;
    try {
      crmData = JSON.parse(responseText);
    } catch (parseError) {
      console.error('Failed to parse CRM response as JSON:', parseError);
      // If parsing fails but response is OK, consider it a success
      if (crmApiResponse.ok) {
        console.log('Response was OK but not JSON, treating as success');
        return new Response(
          JSON.stringify({ 
            success: true,
            message: 'CRM data sent successfully',
            raw_response: responseText
          }),
          { 
            status: 200, 
            headers: { 'Content-Type': 'application/json' }
          }
        );
      }
      throw new Error(`CRM returned non-JSON response: ${responseText.substring(0, 200)}`);
    }

    // Check for success based on your CRM's response structure
    // Your CRM returns { status: 'Success', message: '...', status_code: 200 }
    const isSuccess = crmApiResponse.ok && (
      crmData?.status_code === 200 ||      // Check status_code (your CRM uses this)
      crmData?.status === 200 ||           // Alternative check
      crmData?.status === 'Success' ||     // Check status string
      crmData?.success === true            // Alternative success flag
    );

    if (!isSuccess) {
      console.error('CRM API returned error:', crmData);
      throw new Error(`CRM API returned error: ${crmData?.message || 'Unknown error'}`);
    }

    console.log('✅ CRM data sent successfully:', crmData);

    return new Response(
      JSON.stringify({ 
        success: true,
        message: 'CRM data sent successfully',
        crm_response: crmData
      }),
      { 
        status: 200, 
        headers: { 'Content-Type': 'application/json' }
      }
    );

  } catch (error) {
    console.error('CRM API endpoint error:', error);
    
    return new Response(
      JSON.stringify({ 
        success: false,
        error: 'Failed to send data to CRM',
        details: process.env.NODE_ENV === 'development' ? (error as Error).message : undefined
      }),
      { 
        status: 500, 
        headers: { 'Content-Type': 'application/json' }
      }
    );
  } finally {
    if (connection) {
      connection.release();
    }
  }
}