import { supabase } from "@/lib/supabase"; export type TableroCdcUserAccess = { email: string; fullName: string | null; role: string; isActive: boolean; canDeleteProjects: boolean; canManageInternalPricing: boolean; canControlPricingSummary: boolean; }; type AccessRow = { email?: string | null; full_name?: string | null; role?: string | null; is_active?: boolean | null; can_delete_projects?: boolean | null; can_manage_internal_pricing?: boolean | null; can_control_pricing_summary?: boolean | null; }; function normalizeEmail(email: string | null | undefined): string { return String(email ?? "") .trim() .toLowerCase(); } function normalizeAccessRow(row: AccessRow | null | undefined): TableroCdcUserAccess | null { if (!row?.email || row.is_active !== true) return null; return { email: normalizeEmail(row.email), fullName: row.full_name ?? null, role: String(row.role || "user").trim() || "user", isActive: true, canDeleteProjects: row.can_delete_projects === true, canManageInternalPricing: row.can_manage_internal_pricing === true, canControlPricingSummary: row.can_control_pricing_summary === true, }; } export async function getActiveTableroCdcAccess( email: string | null | undefined, ): Promise { const normalizedEmail = normalizeEmail(email); if (!normalizedEmail) return null; const { data, error } = await supabase .from("tablero_cdc_allowed_users") .select( "email, full_name, role, is_active, can_delete_projects, can_manage_internal_pricing, can_control_pricing_summary", ) .eq("email", normalizedEmail) .eq("is_active", true) .maybeSingle(); if (error) { throw error; } return normalizeAccessRow(data as AccessRow | null); } export async function getCurrentTableroCdcAccess(): Promise { const { data, error } = await supabase.auth.getUser(); if (error || !data.user) { throw new Error("No hay una sesión activa de Supabase."); } const access = await getActiveTableroCdcAccess(data.user.email); if (!access) { throw new Error("Tu correo no está autorizado para acceder al Tablero CDC."); } return access; }