import { useQuery } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "./use-auth";

export function usePermissions() {
  const { user } = useAuth();

  const { data: userRoles = [] } = useQuery({
    queryKey: ["my-roles", user?.id],
    enabled: !!user,
    queryFn: async () => {
      const { data, error } = await supabase
        .from("user_roles")
        .select("role")
        .eq("user_id", user!.id);
      if (error) throw error;
      return data.map((r) => r.role);
    },
  });

  const { data: myPermissions = [] } = useQuery({
    queryKey: ["my-permissions", user?.id],
    enabled: !!user,
    queryFn: async () => {
      // Get user's custom_role_id from profile
      const { data: profile } = await supabase
        .from("profiles")
        .select("custom_role_id")
        .eq("id", user!.id)
        .single();

      if (!profile?.custom_role_id) return [] as string[];

      // Get permissions for that role
      const { data: rolePerms } = await supabase
        .from("role_permissions")
        .select("permission_id")
        .eq("role_id", profile.custom_role_id);

      if (!rolePerms?.length) return [] as string[];

      const permIds = rolePerms.map((rp) => rp.permission_id);
      const { data: perms } = await supabase
        .from("permissions")
        .select("name")
        .in("id", permIds);

      // Check overrides
      const { data: overrides } = await supabase
        .from("user_permission_overrides")
        .select("permission_id, granted")
        .eq("user_id", user!.id);

      const overrideMap = new Map(
        (overrides || []).map((o) => [o.permission_id, o.granted])
      );

      // Build final permission list
      const basePerms = (perms || []).map((p) => p.name);

      // Add granted overrides
      if (overrides?.length) {
        const grantedIds = overrides.filter((o) => o.granted).map((o) => o.permission_id);
        if (grantedIds.length) {
          const { data: extraPerms } = await supabase
            .from("permissions")
            .select("name")
            .in("id", grantedIds);
          if (extraPerms) {
            for (const ep of extraPerms) {
              if (!basePerms.includes(ep.name)) basePerms.push(ep.name);
            }
          }
        }

        // Remove denied overrides
        const deniedIds = overrides.filter((o) => !o.granted).map((o) => o.permission_id);
        if (deniedIds.length) {
          const { data: deniedPerms } = await supabase
            .from("permissions")
            .select("name")
            .in("id", deniedIds);
          if (deniedPerms) {
            const deniedNames = deniedPerms.map((p) => p.name);
            return basePerms.filter((p) => !deniedNames.includes(p));
          }
        }
      }

      return basePerms;
    },
  });

  const isAdmin = userRoles.includes("admin");
  const isStaff = userRoles.includes("staff") || isAdmin;

  const hasPermission = (permission: string): boolean => {
    if (isAdmin) return true;
    return myPermissions.includes(permission);
  };

  const hasAnyPermission = (permissions: string[]): boolean => {
    if (isAdmin) return true;
    return permissions.some((p) => myPermissions.includes(p));
  };

  return {
    userRoles,
    myPermissions,
    isAdmin,
    isStaff,
    hasPermission,
    hasAnyPermission,
  };
}
