import { usePage } from '@inertiajs/react';

import type { PageProps } from '@/types';
import type { SiteSummary } from '@/types';

export interface UseSiteScopeReturn {
  /** The currently active site from Inertia shared props (first site if multiple). */
  site: SiteSummary | null;
  /** The site's numeric ID, or null if no site is active. */
  siteId: number | null;
  /** True if the current user can edit site content (role: owner, admin, or editor). */
  canEdit: boolean;
  /** True if the current user can manage site settings (role: owner or admin). */
  canAdmin: boolean;
}

/**
 * DEBT-006: Reads current site context from Inertia shared props.
 *
 * In site-scoped pages, the active site is passed as the first item in the
 * `sites` array (after HandleInertiaRequests middleware hydration).
 * For pages with a single site in context, this hook provides a clean API.
 *
 * Usage:
 *   const { site, siteId, canEdit, canAdmin } = useSiteScope();
 *   if (!canEdit) return <AccessDenied />;
 */
export function useSiteScope(): UseSiteScopeReturn {
  const { sites } = usePage<PageProps>().props;

  const site = sites?.[0] ?? null;
  const siteId = site?.id ?? null;

  const canEdit =
    site !== null &&
    (site.current_role === 'owner' ||
      site.current_role === 'admin' ||
      site.current_role === 'editor');

  const canAdmin =
    site !== null &&
    (site.current_role === 'owner' || site.current_role === 'admin');

  return { site, siteId, canEdit, canAdmin };
}
