import { NextRequest } 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 connection = await pool.getConnection();
  
  try {
    const body = await request.json();
    const { planId } = body;

    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
       FROM study_plans WHERE id = ?`,
      [planId]
    );

    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 free_consulations structure)
    const crmPayload = {
      full_name: plan.full_name,
      email: plan.email,
      phone_number: plan.phone,
      last_education: plan.last_education,
      education_level: plan.education_level,
      cgpa: plan.cgpa,
      study_gap: plan.study_gap,
      interested_country: plan.target_country, // Using interested_country to match free_consulations
      target_university: plan.target_university,
      target_course: plan.target_course,
      word_count: plan.word_count,
      response_style: plan.response_style,
      study_plan: plan.study_plan, // The final AI-generated content
    };

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

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

    const crmData = await crmApiResponse.json();
    
    if (crmData?.status_code !== 200) {
      throw new Error('CRM API returned non-success status');
    }

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