"use client"

import { useCallback, useMemo } from "react"
import { useSession } from "next-auth/react"
import type { Permission, Role } from "@/shared/types/permissions"

/**
 * Client-side permission hook.
 *
 * Hydration safety: `useSession()` returns `null`/`loading` on the server and
 * during the first client render. Callers should gate permission-dependent UI
 * behind `status === "authenticated"` (returned by `useSession`) or render a
 * skeleton/placeholder while loading to avoid hydration mismatches.
 */
export function usePermission() {
  const { data: session, status } = useSession()

  const permissions = useMemo<Permission[]>(
    () => session?.user?.permissions ?? [],
    [session?.user?.permissions]
  )
  const roles = useMemo<Role[]>(
    () => session?.user?.roles ?? [],
    [session?.user?.roles]
  )

  const hasPermission = useCallback(
    (permission: Permission): boolean => permissions.includes(permission),
    [permissions]
  )
  const hasAnyPermission = useCallback(
    (...perms: Permission[]): boolean => perms.some((p) => permissions.includes(p)),
    [permissions]
  )
  const hasAllPermissions = useCallback(
    (...perms: Permission[]): boolean => perms.every((p) => permissions.includes(p)),
    [permissions]
  )
  const hasRole = useCallback(
    (role: Role): boolean => roles.includes(role),
    [roles]
  )

  return {
    permissions,
    roles,
    status,
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    hasRole,
  }
}
