// app/api/frontend/foreign-students/report/route.js
import { NextResponse } from 'next/server';
import pool from "../../../../../lib/db/db";

export async function POST(request) {

    const connection = await pool.getConnection();

  try {
    
    
    // Parse the request body
    const body = await request.json();
    const { student_id, name, email, phone, message } = body;
    
    // Validate required fields
    if (!student_id || !name || !email || !message || !phone) {
      return NextResponse.json(
        { 
          success: false, 
          error: 'Missing required fields: student_id, name, phone, email, and message are required' 
        },
        { status: 400 }
      );
    }

    connection.beginTransaction();
    
    // Validate email format
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return NextResponse.json(
        { 
          success: false, 
          error: 'Invalid email format' 
        },
        { status: 400 }
      );
    }
    
    // Check if the student exists
    const checkStudentQuery = `SELECT id FROM foreign_students WHERE id = ? AND is_active = 1`;
    const [studentCheck] = await connection.execute(checkStudentQuery, [student_id]);
    
    if (studentCheck.length === 0) {
      return NextResponse.json(
        { 
          success: false, 
          error: 'Student not found or inactive' 
        },
        { status: 404 }
      );
    }
    
    // Insert the complaint into database
    const insertQuery = `
      INSERT INTO foreign_student_complaints 
      (student_id, name, email, phone, message, created_at, updated_at)
      VALUES (?, ?, ?, ?, ?, NOW(), NOW())
    `;
    
    const values = [student_id, name, email, phone || null, message];
    
    const [result] = await connection.execute(insertQuery, values);
    
    if(result.insertId === 0) {
      return NextResponse.json(
        {
          success: false,
          error: 'Failed to submit report'
        },
        { status: 500 }
      );
    }

    // Prepare payload for CRM
    const crmPayload = {
        student_id,
        name,
        email,
        phone,
        message
    };

    // Send to CRM API
    let crmResponse;
    try {
        crmResponse = await fetch(
        "https://crm-universitiespage.com/reactapis/api/website_foreign_student/store_complaint",
        {
            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 crmData = await crmResponse.json();

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

    } catch (crmError) {
        await connection.rollback();
        console.error('CRM API Error:', crmError);
        
        return NextResponse.json(
        {
            success: false,
            message: "Failed to submit your form to CRM. Please try again later."
        },
        { status: 502 } // Bad Gateway
        );
    }

    connection.commit();
    
    return NextResponse.json({
      success: true,
      message: 'Report submitted successfully',
      data: {
        complaint_id: result.insertId,
      }
    });
    
  } catch (error) {
    await connection.rollback();
    console.error('Error submitting report:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: 'Failed to submit report',
        details: error.message 
      },
      { status: 500 }
    );
  } finally {
    connection.release();
  }
}