// File: app/api/comparison-store/route.js
import { NextRequest, NextResponse } from 'next/server';
import pool from '../../../../../lib/db/db';
import { ResultSetHeader, RowDataPacket } from 'mysql2';

export async function POST(request: NextRequest) {
  const connection = await pool.getConnection();

  try {
    const body = await request.json();
    
    const {
      name,
      email,
      phone,
      comparison_type,
      compared_items
    } = body;

    // Validate required fields
    if (!name || !email || !phone || !comparison_type || !compared_items) {
      return NextResponse.json(
        { 
          success: false, 
          message: 'Name, email, phone, comparison_type, and compared_items are required' 
        },
        { status: 400 }
      );
    }

    // Validate comparison_type
    if (!['university', 'course'].includes(comparison_type)) {
      return NextResponse.json(
        { 
          success: false, 
          message: 'comparison_type must be either "university" or "course"' 
        },
        { status: 400 }
      );
    }

    // Validate compared_items is an array
    if (!Array.isArray(compared_items) || compared_items.length < 2) {
      return NextResponse.json(
        { 
          success: false, 
          message: 'compared_items must be an array with at least 2 items' 
        },
        { status: 400 }
      );
    }

    await connection.beginTransaction();

    let newNameArray = [];

    if(comparison_type === "university")
    {
      compared_items.map(async (item) => {
        const [query] = await connection.query("SELECT id, name FROM university_details WHERE id = ?", [item])
        newNameArray.push(query[0].name)
      })
    }
    else if(comparison_type === "course")
    {
      compared_items.map(async (item) => {
        const [query] = await connection.query("SELECT id, name FROM courses WHERE id = ?", [item])
        newNameArray.push(query[0].name)
      })
    }
    else
    {
      return NextResponse.json(
        {
          success: false,
          message: 'comparison_type must be either "university" or "course"'
        },
        { status: 400 }
      );
    }

    // Insert into database
    const insertQuery = `
      INSERT INTO comparison_tool_submissions (
        name, 
        email, 
        phone, 
        comparison_type, 
        compared_items
      ) VALUES (?, ?, ?, ?, ?)
    `;
    
    const insertValues = [
      name,
      email,
      phone,
      comparison_type,
      JSON.stringify(compared_items), // Store as JSON array
    ];
    
    const [result] = await connection.query<ResultSetHeader>(insertQuery, insertValues);
    const submissionId = result.insertId;

    // Send to CRM API (optional - similar to your eligibility calculator)
    const crmPayload = {
      name,
      email,
      phone,
      comparison_type,
      compared_items: newNameArray,
    };

    try {
      const crmResponse = await fetch(
        "https://crm-universitiespage.com/reactapis/api/website_foreign_student/store_comparison",
        {
          method: "POST",
          body: JSON.stringify(crmPayload),
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `${process.env.CRM_API_KEY || ''}`,
          },
        }
      );

      if (!crmResponse.ok) {
        console.warn(`CRM API responded with status: ${crmResponse.status}`);
        // Don't fail if CRM fails, just log it
        await connection.rollback();
        return NextResponse.json(
          {
            success: false,
            message: 'Failed to store comparison data',
            error: 'CRM API failure'
          },
          { status: 500 }
        );
      }
    } catch (crmError) {
      console.warn('CRM API Error (non-critical):', crmError);
      // Continue with the transaction even if CRM fails
    }

    await connection.commit();

    return NextResponse.json({
      success: true,
      message: 'Comparison data stored successfully',
      data: { 
        submissionId,
        compared_items_count: compared_items.length,
        comparison_type,
        submittedAt: new Date().toISOString()
      }
    });

  } catch (error) {
    if (connection) {
      await connection.rollback();
    }
    
    console.error('Error storing comparison data:', error);
    return NextResponse.json(
      { 
        success: false, 
        message: 'Failed to store comparison data',
        error: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    );
  } finally {
    if (connection) {
      connection.release();
    }
  }
}