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

interface ConsultantRow extends RowDataPacket {
  id: number;
  user_id: number;
  email: string;
  first_name: string;
  last_name: string;
  phone?: string;
}

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

  try {
    /* =========================
       AUTHORIZATION
    ========================== */
    const authHeader = request.headers.get('authorization');
    const expectedApiKey = `Bearer ${process.env.CRM_API_KEY}`;

    if (!authHeader || authHeader !== expectedApiKey) {
      return NextResponse.json(
        { success: false, message: 'Unauthorized: Invalid API key' },
        { status: 401 }
      );
    }

    /* =========================
       REQUEST BODY
    ========================== */
    const body = await request.json();
    const { consultant_id, action, rejection_reason } = body;

    if (!consultant_id) {
      return NextResponse.json(
        { success: false, message: 'Consultant ID is required' },
        { status: 400 }
      );
    }

    if (!['approve', 'reject'].includes(action)) {
      return NextResponse.json(
        { success: false, message: "Action must be 'approve' or 'reject'" },
        { status: 400 }
      );
    }

    if (action === 'reject' && !rejection_reason?.trim()) {
      return NextResponse.json(
        { success: false, message: 'Rejection reason is required' },
        { status: 400 }
      );
    }

    await connection.beginTransaction();

    /* =========================
       CHECK CONSULTANT
    ========================== */
    const [consultantCheck] = await connection.query<ConsultantRow[]>(
      `
      SELECT c.*, u.email, u.first_name, u.last_name, u.phone
      FROM consultants c
      JOIN users u ON c.user_id = u.id
      WHERE c.user_id = ?
      `,
      [consultant_id]
    );

    if (consultantCheck.length === 0) {
      await connection.rollback();
      return NextResponse.json(
        { success: false, message: 'Consultant not found' },
        { status: 404 }
      );
    }

    const consultant = consultantCheck[0];
    const consultantUserId = consultant.user_id;

    /* =========================
       PREPARE UPDATE DATA
    ========================== */
    const now = new Date().toISOString().slice(0, 19).replace('T', ' ');

    const updateData =
      action === 'approve'
        ? {
            active_profile: '1',
            profile_status: 'approved',
            approved_date: now,
            rejection_reason: null,
            updated_at: now,
          }
        : {
            active_profile: '0',
            profile_status: 'rejected',
            approved_date: null,
            rejection_reason,
            updated_at: now,
          };

    /* =========================
       UPDATE CONSULTANT
    ========================== */
    const [updateResult] = await connection.query<ResultSetHeader>(
      `
      UPDATE consultants
      SET active_profile = ?,
          profile_status = ?,
          approved_date = ?,
          rejection_reason = ?,
          updated_at = ?
      WHERE user_id = ?
      `,
      [
        updateData.active_profile,
        updateData.profile_status,
        updateData.approved_date,
        updateData.rejection_reason,
        updateData.updated_at,
        consultantUserId
      ]
    );

    if (updateResult.affectedRows === 0) {
      await connection.rollback();
      return NextResponse.json(
        { success: false, message: 'Failed to update consultant profile' },
        { status: 500 }
      );
    }

    /* =========================
       UPDATE USER STATUS
    ========================== */
    if (action === 'approve') {
      await connection.query<ResultSetHeader>(
        `UPDATE users SET is_active = '1', updated_at = NOW() WHERE id = ?`,
        [consultantUserId]
      );
    }

    await connection.commit();

    /* =========================
       FETCH UPDATED DATA
    ========================== */
    const [updatedConsultant] = await connection.query<ConsultantRow[]>(
      `
      SELECT 
        c.*,
        u.email,
        u.first_name,
        u.last_name,
        u.phone,
        c.active AS user_active
      FROM consultants c
      JOIN users u ON c.user_id = u.id
      WHERE c.user_id = ?
      `,
      [consultant_id]
    );

    return NextResponse.json(
      {
        success: true,
        message:
          action === 'approve'
            ? 'Consultant profile approved successfully'
            : 'Consultant profile rejected successfully',
        data: {
          consultant_id,
          user_id: consultantUserId,
          action,
          ...updateData,
          consultant_details: updatedConsultant[0] || {},
        },
      },
      { status: 200 }
    );
  } catch (error: any) {
    try {
      await connection.rollback();
    } catch {}

    console.error('CRM Approval API error:', error);

    return NextResponse.json(
      { success: false, message: error.message || 'Internal server error' },
      { status: 500 }
    );
  } finally {
    connection.release();
  }
}
