"use client";

import { useAuth } from "@/lib/auth-context";
import { getRoleNames } from "@/lib/types";
import { useCallback, useMemo } from "react";

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

  const roles = useMemo(
    () => getRoleNames(user?.roles ?? []),
    [user?.roles]
  );

  const permissions = useMemo(
    () => user?.permissions ?? [],
    [user?.permissions]
  );

  const hasRole = useCallback(
    (role: string | string[]) => {
      if (!user) return false;
      const check = Array.isArray(role) ? role : [role];
      return check.some((r) => roles.includes(r));
    },
    [user, roles]
  );

  const hasPermission = useCallback(
    (permission: string | string[]) => {
      if (!user) return false;
      // Admins have all permissions
      if (roles.includes("admin")) return true;
      const check = Array.isArray(permission) ? permission : [permission];
      return check.some((p) => permissions.includes(p));
    },
    [user, roles, permissions]
  );

  const hasAnyRole = useCallback(
    (roleList: string[]) => {
      if (!user) return false;
      return roleList.some((r) => roles.includes(r));
    },
    [user, roles]
  );

  const isAdmin = useMemo(() => roles.includes("admin"), [roles]);
  const isContentManager = useMemo(
    () => roles.includes("admin") || roles.includes("seller") || roles.includes("company"),
    [roles]
  );

  return {
    roles,
    permissions,
    hasRole,
    hasPermission,
    hasAnyRole,
    isAdmin,
    isContentManager,
    user,
  };
}
