import { createContext, useContext, type ReactNode } from "react";
import type { IConsent } from "../consent.interface";

const ConsentContext = createContext<IConsent | null>(null);

export class ConsentContextError extends Error {
  constructor() {
    super("useConsent() must be called within a <ConsentProvider>.");
    this.name = "ConsentContextError";
  }
}

export function ConsentProvider({
  value,
  children,
}: {
  value: IConsent;
  children: ReactNode;
}) {
  return (
    <ConsentContext.Provider value={value}>{children}</ConsentContext.Provider>
  );
}

export function useConsent(): IConsent {
  const consent = useContext(ConsentContext);
  if (consent === null) {
    throw new ConsentContextError();
  }
  return consent;
}
