import { authClient } from '@lib/auth-client';
import { useEffect, useState } from 'react';

function useHasPermission(
  resource: string,
  action: string,
  houseCheck: boolean = false,
) {
  const { data: activeOrganization } = authClient.useActiveOrganization();
  const [hasPermission, setHasPermission] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (houseCheck && !activeOrganization?.id) {
      setIsLoading(false);
      setHasPermission(false);
      return;
    }

    const checkPermission = async () => {
      setIsLoading(true);
      try {
        const option = {
          permissions: {
            [resource]: [action],
          },
        };
        const access = houseCheck
          ? await authClient.organization.hasPermission(option)
          : await authClient.admin.hasPermission(option);

        setHasPermission(access.data?.success ?? false);
      } catch (error) {
        console.error('Permission check failed:', error);
      } finally {
        setIsLoading(false);
      }
    };
    checkPermission();
  }, [resource, action, houseCheck, activeOrganization?.id]);

  return { hasPermission, isLoading };
}

export default useHasPermission;
