import { createSupabaseServerClient } from "./supabase/server";

export type AppRole = "admin" | "graphic_designer" | "video_editor";
export type DashboardModule = "Overview" | "Monthly plan" | "Tasks" | "Calendar" | "Clients" | "Team" | "Attendance" | "Company" | "Reports";
export type CurrentProfile = { id: string; full_name: string; role: AppRole; active: boolean; designation?: string | null; custom_role?: string | null; module_permissions?: DashboardModule[] | null; phone?: string | null; organization_id: string; workspace_role: string; department_id?: string | null };

export async function getCurrentProfile(): Promise<CurrentProfile | null> {
  const supabase = await createSupabaseServerClient();
  if (!supabase) return null;
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return null;
  const { data } = await supabase.from("profiles").select("id,full_name,role,active,designation,custom_role,module_permissions,phone,organization_id,workspace_role,department_id").eq("id", user.id).single();
  return data as CurrentProfile | null;
}

export async function authorize(allowed: AppRole[]) {
  const profile = await getCurrentProfile();
  if (!profile?.active || !allowed.includes(profile.role)) return null;
  return profile;
}
