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

import { NextResponse } from 'next/server';
import  { RowDataPacket } from 'mysql2/promise';

import { getDBConnection } from '@/lib/db'; // adjust path as needed


interface TopProvider extends RowDataPacket {
  doctor_id: number;
  name: string;
  image: string | null;
  address: string | null;
  zip_code: string | null;
  degree: string | null;
  visit_count: number;
}

export async function GET(request: Request) {
  try {
    const url = new URL(request.url);
    const companyId = url.searchParams.get('companyId');

    const connection = await getDBConnection();

    // Base query
    let query = `
      SELECT
        ap.doctor_id,
        u.name AS name,
        u.profile AS image,
        u.address AS address,
        u.z_code AS zip_code,
        u.degree AS degree,
        COUNT(ap.id) AS visit_count
      FROM
        appointments ap
      INNER JOIN
        users u ON ap.doctor_id = u.id
    `;

    const params: (string | number)[] = [];

    // Add WHERE clause if companyId exists
    if (companyId) {
      query += ` WHERE u.company_id = ? `;
      params.push(companyId);
    }

    query += `
      GROUP BY
        ap.doctor_id
      ORDER BY
        visit_count DESC
      LIMIT 5
    `;

    const [rows] = await connection.execute<TopProvider[]>(query, params);

    await connection.end();

    return NextResponse.json(rows);
  } catch (error) {
    // console.error('Top Providers API Error:', error);
    return NextResponse.json({ error: 'Failed to fetch top providers' }, { status: 500 });
  }
}
