// app/api/frontend/scholarship-applications/route.js
import { NextResponse, NextRequest } from 'next/server';
import pool from '../../../../lib/db/db';
import { ResultSetHeader, RowDataPacket } from 'mysql2';

  export async function POST(request: NextRequest) {
    // Check authorization header
    const incomingHeaders = request.headers.get("authorization");

    if (incomingHeaders !== 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 {
      name,
      email,
      phonecode,
      phone_number,
      last_education,
      office_to_visit,
      scholarship_id,
      scholarship_title,
    } = body;

    // Validation with proper typing
    const errors: Record<string, string[]> = {};
    if (!name?.trim()) errors.name = ['Name is required'];
    if (!email?.trim()) errors.email = ['Email is required'];
    if (!phone_number?.trim()) errors.phone_number = ['Phone number is required'];
    if (!last_education?.trim()) errors.last_education = ['Last education is required'];
    if (!office_to_visit?.trim()) errors.office_to_visit = ['Office to visit is required'];
    if (!scholarship_id) errors.scholarship_id = ['Scholarship ID is required'];

    if (Object.keys(errors).length > 0) {
      return NextResponse.json(
        { success: false, errors },
        { status: 422 }
      );
    }

    await connection.beginTransaction();

    const newPhoneNumber = `${phonecode}${phone_number}`;

    const [checkScholarship] = await connection.query<RowDataPacket[]>(
      'SELECT * FROM scholarships WHERE id = ?',
      [scholarship_id]
    );

    if(checkScholarship.length === 0)
    {
      return NextResponse.json(
        { success: false, message: 'Scholarship not found' },
        { status: 404 }
      );
    }

    // Insert application into database
    const [result] = await connection.query<ResultSetHeader>(
      `INSERT INTO scholarship_applications 
       (name, email, phone_number, last_education, office_to_visit, scholarship_id, scholarship_title, created_at) 
       VALUES (?, ?, ?, ?, ?, ?, ?, NOW())`,
      [name, email, newPhoneNumber, last_education, office_to_visit, scholarship_id, scholarship_title]
    );

    const payload = {
      name: name,
      email: email,
      phone_number: newPhoneNumber,
      last_education: last_education,
      office_to_visit: office_to_visit,
      scholarship_title: scholarship_title
    }

    // Send to CRM API
    let crmResponse;
    try {
      crmResponse = await fetch(
        "http://crm-universitiespage.com/reactapis/api/website_scholarship_crm/store",
        {
          method: "POST",
          body: JSON.stringify(payload),
          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
      );
    }

    await connection.commit();

    return NextResponse.json(
      {
        success: true,
        message: 'Scholarship application submitted successfully! Our team will contact you shortly.',
        data: { id: result.insertId }
      },
      { status: 201 }
    );

  } catch (error) {
    await connection.rollback();
    console.error('Scholarship application error:', error);
    return NextResponse.json(
      {
        success: false,
        message: 'Failed to submit scholarship application. Please try again.'
      },
      { status: 500 }
    );
  } finally {
    connection.release();
  }
}