/* 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
    const query = `
    SELECT 
      vt.*, 
      CONCAT(c.first_name, ' ', c.last_name) AS company_name 
    FROM visit_type vt
    LEFT JOIN comapniese c ON vt.company_id = c.id 
    WHERE vt.company_id = ? 
    ORDER BY vt.id ASC
  `;
  
  const params = [companyId];

    

    // Add WHERE clause only if companyId is provided
  
 
    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, company_id, manager_id } = body;

    // ✅ Correct field check
    if (!name || !company_id || !manager_id) {
      return NextResponse.json({ error: 'Missing fields' }, { status: 400 });
    }

    const connection = await getDBConnection();
    const [result] = await connection.execute(
      'INSERT INTO visit_type (name, company_id, manager_id) VALUES (?, ?, ?)',
      [name, company_id, manager_id] // ✅ Correct order
    );
    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 });
  }
}
