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

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

export async function POST(request: NextRequest) {
  const { userId, companyId } = await request.json();

  if (!userId || !companyId) {
    return NextResponse.json({ error: 'Missing parameters' }, { status: 400 });
  }

  const connection = await getDBConnection();

  try {
    // Step 1: Fetch all providers for the given company
    const [rows] = await connection.execute(
      "SELECT id FROM users WHERE role='doctor' and company_id = ?",
      [companyId]
    );
    const providers = rows as { id: number }[];

    if (providers.length === 0) {
      return NextResponse.json({ error: 'No providers found for this company' }, { status: 404 });
    }

    // Step 2: Loop through providers and check for existing requests
    const requestsToInsert = [];
    for (const provider of providers) {
      const [existing] = await connection.execute(
        'SELECT * FROM requests WHERE doctor_id = ? AND user_id = ? AND status IN ("pending", "accepted", "active")',
        [provider.id, userId]
      );

      const existingRequests = existing as any[];

      if (existingRequests.length === 0) {
        requestsToInsert.push(
          connection.execute(
            'INSERT INTO requests (doctor_id, user_id, company_id, status, time, date) VALUES (?, ?, ?, ?, NOW(), NOW())',
            [provider.id, userId, companyId, 'pending']
          )
        );
      }
    }

    if (requestsToInsert.length > 0) {
      await Promise.all(requestsToInsert);
      return NextResponse.json({ message: 'Requests broadcasted successfully' });
    } else {
      return NextResponse.json({ message: 'All providers already have a pending or active request for this patient' });
    }

  } catch (err) {
    // console.error(err);
    return NextResponse.json({ error: 'Database query failed' }, { status: 500 });
  } finally {
    await connection.end();
  }
}
