import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import type { Tables, Enums } from "@/integrations/supabase/types";

interface UserProfile {
  profile: Tables<"profiles"> | null;
  roles: Enums<"app_role">[];
  loading: boolean;
}

export function useUserProfile(userId?: string): UserProfile {
  const [profile, setProfile] = useState<Tables<"profiles"> | null>(null);
  const [roles, setRoles] = useState<Enums<"app_role">[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!userId) {
      setLoading(false);
      return;
    }

    async function fetchProfile() {
      const [profileRes, rolesRes] = await Promise.all([
        supabase.from("profiles").select("*").eq("user_id", userId!).single(),
        supabase.from("user_roles").select("role").eq("user_id", userId!),
      ]);

      if (profileRes.data) setProfile(profileRes.data);
      if (rolesRes.data) setRoles(rolesRes.data.map((r) => r.role));
      setLoading(false);
    }

    fetchProfile();
  }, [userId]);

  return { profile, roles, loading };
}
