"use client";

import { useEffect, useState } from "react";

import { canEditMasterCode } from "@/lib/roles";

type MeResponse = {
  data?: {
    role?: string;
  };
};

export function useCurrentUser() {
  const [role, setRole] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;

    async function loadCurrentUser() {
      try {
        const response = await fetch("/api/v1/auth/me", { cache: "no-store" });
        const payload = (await response.json()) as MeResponse;
        if (!cancelled && response.ok) {
          setRole(payload.data?.role ?? null);
        }
      } catch {
        if (!cancelled) {
          setRole(null);
        }
      }
    }

    void loadCurrentUser();

    return () => {
      cancelled = true;
    };
  }, []);

  return {
    role,
    canEditCode: canEditMasterCode(role)
  };
}
