import type { Role, PlatformRole } from '../types/auth';

export const GLOBAL_ADMIN_RFC = 'HTS240708LJA';

/** Roles que son superset (implican todos los demás platform roles). */
const SUPERSET_ROLES: PlatformRole[] = ['platform_admin', 'platform_ti'];

/**
 * "Admin global" = staff interno de Horux 360 con rol `platform_admin` o `platform_ti`.
 *
 * Primero checa `platformRoles` del user (nueva fuente de verdad post-migración).
 * Si no hay platformRoles (JWT viejo, sesión pre-deploy), cae al check legacy
 * por RFC + rol owner del tenant HTS240708LJA.
 *
 * Código nuevo debería preferir `hasPlatformRoleFromArray(platformRoles, 'platform_admin')`.
 */
export function isGlobalAdminRfc(
  tenantRfc: string | undefined,
  role: string | undefined,
  platformRoles?: PlatformRole[] | null,
): boolean {
  // Nueva fuente: platform_admin o platform_ti en user_platform_roles
  if (platformRoles && SUPERSET_ROLES.some(r => platformRoles.includes(r))) return true;
  // Fallback legacy: owner del tenant con RFC admin global
  return role === 'owner' && tenantRfc === GLOBAL_ADMIN_RFC;
}

/** ¿El user tiene algún rol de plataforma (staff interno)? */
export function isPlatformStaffFromRoles(platformRoles?: PlatformRole[] | null): boolean {
  return !!platformRoles && platformRoles.length > 0;
}

/** ¿El user tiene el rol de plataforma indicado? admin y ti implican todos. */
export function hasPlatformRoleFromArray(
  platformRoles: PlatformRole[] | undefined | null,
  role: PlatformRole,
): boolean {
  if (!platformRoles) return false;
  if (SUPERSET_ROLES.some(r => platformRoles.includes(r))) return true;
  return platformRoles.includes(role);
}

export const ROLES = {
  owner: {
    name: 'Dueño',
    permissions: ['read', 'write', 'delete', 'manage_users', 'manage_settings'],
  },
  cfo: {
    name: 'CFO',
    permissions: ['read', 'write', 'delete', 'manage_users', 'manage_settings'],
  },
  contador: {
    name: 'Contador',
    permissions: ['read', 'write', 'resolve_alertas'],
  },
  auxiliar: {
    name: 'Auxiliar',
    permissions: ['read', 'write', 'resolve_alertas'],
  },
  visor: {
    name: 'Visor',
    permissions: ['read'],
  },
  supervisor: {
    name: 'Supervisor',
    permissions: ['read', 'write', 'resolve_alertas', 'manage_carteras'],
  },
  cliente: {
    name: 'Cliente',
    permissions: ['read'],
  },
} as const;

export function hasPermission(role: Role, permission: string): boolean {
  return ROLES[role].permissions.includes(permission as any);
}
