/* 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(req: NextRequest) {
  const { email, password } = await req.json();

  try {
    const connection = await getDBConnection();
    console.log("✅ Database connection established");

    // Get user from database
    const [rows]: any = await connection.execute(
      'SELECT id, email, password, name, role FROM users WHERE email = ?',
      [email]
    );

    if (rows.length === 0) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    const user = rows[0];

    // Validate password
    // const isPasswordCorrect = await bcrypt.compare(password, user.password);
    // if (!isPasswordCorrect) {
    //   return NextResponse.json({ error: 'Invalid password' }, { status: 401 });
    // }

    if (password !== user.password) {
      return NextResponse.json({ error: 'Invalid password' }, { status: 401 });
    }
    

    let companies = [];

    // If manager, fetch associated companies
    if (user.role === 'manager') {
      const [companyRows]: any = await connection.execute(
        `SELECT c.id, CONCAT(c.first_name, ' ', c.last_name) AS name
         FROM manager_companies mc
         JOIN comapniese c ON c.id = mc.company_id
         WHERE mc.manager_id = ?`,
        [user.id]
      );

      // Add "active: true" to the first company
      companies = companyRows.map((company: any, index: number) => ({
        id: company.id,
        name: company.name,
        active: index === 0, // First one is active
      }));
    }  

    // Success response
    return NextResponse.json({
      message: 'Login successful',
      user: {
        id: user.id,
        name: user.name,
        email: user.email,
        role: user.role,
        companies: companies,
      },
    });

  } catch (err) {
    console.error('❌ Login API Error:', err);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
