/* eslint-disable -- temporary disable for development/testing purposes */

import { NextRequest, NextResponse } from 'next/server';
import { getDBConnection } from '@/lib/db';

export async function POST(request: NextRequest) {
  const { patientId, assignedId, type, companyId, category } = await request.json();

  // Validate input parameters
  if (!patientId || !companyId || !assignedId || !type || !category) {
    return NextResponse.json({ error: 'Missing parameters' }, { status: 400 });
  }

  console.log({ patientId, assignedId, type, companyId, category }); // debug payload

  const connection = await getDBConnection();

  try {
    // Check for existing assignment
    const [existing] = await connection.execute(
      'SELECT * FROM requests WHERE user_id = ? AND company_id = ? AND doctor_id = ?',
      [patientId, companyId, assignedId]
    );

    const existingRequests = existing as any[];

    if (existingRequests.length > 0) {
      return NextResponse.json(
        { message: `${type.charAt(0).toUpperCase() + type.slice(1)} is already assigned to this patient.` },
        { status: 400 }
      );
    }

    // Corrected INSERT statement
    await connection.execute(
      'INSERT INTO requests (doctor_id, user_id, company_id, status, category, time, date) VALUES (?, ?, ?, ?, ?, NOW(), NOW())',
      [assignedId, patientId, companyId, 'pending', category]
    );

    return NextResponse.json({
      message: `${type.charAt(0).toUpperCase() + type.slice(1)} assigned successfully!`
    });

  } catch (err) {
    console.error("Database error raw:", err); // print entire error object
  
    let errorMessage = 'Database query failed';
  
    if (err instanceof Error) {
      errorMessage = err.message;
    } else if (typeof err === 'object' && err !== null) {
      errorMessage = JSON.stringify(err); // capture structured unknown errors
    } else if (typeof err === 'string') {
      errorMessage = err;
    }
  
    return NextResponse.json({ error: errorMessage }, { status: 500 });
  } finally {
    await connection.end();
  }
}
