import type { Pool } from 'pg';
import type { Role } from '@horux/shared';

export async function getEntidadesVisibles(pool: Pool, userId: string, role: Role): Promise<string[]> {
  let query: string;
  let params: unknown[];

  switch (role) {
    case 'owner':
    case 'cfo':
    case 'contador':
    case 'visor':
      // Full access to all active entities
      query = 'SELECT id FROM entidades_gestionadas WHERE active = true';
      params = [];
      break;

    case 'supervisor':
      // Entities assigned to supervisor: via entidades_gestionadas.supervisor_user_id
      // OR via cartera_entidades in carteras assigned to this supervisor
      query = `
        SELECT DISTINCT id FROM (
          SELECT id FROM entidades_gestionadas WHERE supervisor_user_id = $1 AND active = true
          UNION
          SELECT ce.entidad_id AS id
          FROM cartera_entidades ce
          JOIN carteras c ON c.id = ce.cartera_id AND c.parent_id IS NULL
          JOIN entidades_gestionadas e ON e.id = ce.entidad_id
          WHERE c.supervisor_user_id = $1 AND e.active = true
        ) sub
      `;
      params = [userId];
      break;

    case 'auxiliar':
      // Entities from subcarteras assigned to this auxiliar
      // OR from legacy cartera_auxiliares (backward compat)
      query = `
        SELECT DISTINCT id FROM (
          SELECT ce.entidad_id AS id
          FROM cartera_entidades ce
          JOIN carteras c ON c.id = ce.cartera_id
          JOIN entidades_gestionadas e ON e.id = ce.entidad_id
          WHERE c.auxiliar_user_id = $1 AND e.active = true
          UNION
          SELECT ce.entidad_id AS id
          FROM cartera_entidades ce
          JOIN cartera_auxiliares ca ON ca.cartera_id = ce.cartera_id
          JOIN entidades_gestionadas e ON e.id = ce.entidad_id
          WHERE ca.auxiliar_user_id = $1 AND e.active = true
        ) sub
      `;
      params = [userId];
      break;

    case 'cliente':
      // Only entities explicitly granted via cliente_accesos
      query = 'SELECT entidad_id AS id FROM cliente_accesos WHERE user_id = $1';
      params = [userId];
      break;

    default:
      return [];
  }

  const { rows } = await pool.query(query, params);
  return rows.map(r => r.id);
}
