/* 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 GET(request: NextRequest) {
  const companyId = request.nextUrl.searchParams.get('companyId') || null;

  try {
    const connection = await getDBConnection();

    // Base query
    let query = `
      SELECT 
        a.*, 
        a.company_id, 
        u.name AS user_name, 
        u.email AS user_email,
        d.name AS doctor_name,
        d.email AS doctor_email,
        d.degree AS doctor_degree,
        CONCAT(c.first_name, ' ', c.last_name) AS company_name 
      FROM appointments a 
      JOIN users u ON a.user_id = u.id 
      JOIN users d ON a.doctor_id = d.id 
      LEFT JOIN comapniese c ON a.company_id = c.id
    `;

    const params = [];

    // Add WHERE clause only if companyId is provided
    if (companyId) {
      query += ' WHERE a.company_id = ?';
      params.push(companyId);
    }

    // Add ORDER BY clause after WHERE (or directly if no WHERE)
    query += ' ORDER BY a.date DESC, a.time ASC';

    const [rows] = await connection.execute(query, params);
    await connection.end();

    return NextResponse.json(rows);
  } catch (error) {
    // console.error('GET Error:', error);
    return NextResponse.json({ error: 'Database query failed' }, { status: 500 });
  }
}


export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { name, address } = body;

    if (!name || !address) {
      return NextResponse.json({ error: 'Missing fields' }, { status: 400 });
    }

    const connection = await getDBConnection();
    const [result] = await connection.execute(
      'INSERT INTO companies (name, address) VALUES (?, ?)',
      [name, address]
    );
    await connection.end();

    return NextResponse.json({ message: 'Company added', result });
  } catch (error) {
    // console.error('POST Error:', error);
    return NextResponse.json({ error: 'Insert failed' }, { status: 500 });
  }
}
