"use client";

import type { Domain } from "@domainops/shared-types";
import { createContext, useContext } from "react";

interface DomainContextValue {
  domain: Domain;
  setDomain: (domain: Domain) => void;
  /** Re-reads the domain in the background - the page stays as it is while it loads. */
  reload: () => Promise<void>;
}

export const DomainContext = createContext<DomainContextValue | null>(null);

/**
 * The domain a /domains/{id}/... page belongs to. It is loaded once by the
 * layout and kept there, so saving something on one tab updates it in place
 * instead of reloading the page.
 */
export function useDomain(): DomainContextValue {
  const value = useContext(DomainContext);

  if (!value) throw new Error("useDomain must be used inside a domain page.");

  return value;
}
