"use client";

import { useMemo } from "react";
import { useMe } from "@/hooks/useMe";

const ADMIN_ROLES = new Set(["platform_admin", "tenant_owner", "tenant_admin"]);

export function useCommunicationPermissions() {
  const { me } = useMe();

  return useMemo(() => {
    const extended = me as { roles?: string[]; permissions?: string[] } | null | undefined;
    const roles = new Set(extended?.roles ?? []);
    const isAdmin =
      me?.platform_role === "platform_admin" ||
      [...roles].some((r) => ADMIN_ROLES.has(r));
    const perms = new Set(extended?.permissions ?? []);

    const can = (permission: string) => {
      if (isAdmin) return true;
      if (perms.has("communication.manage")) return true;
      if (perms.has(permission)) return true;
      if (permission.endsWith(".view") && perms.has("communication.view")) return true;
      const parts = permission.split(".");
      if (parts.length >= 2 && perms.has(`${parts[0]}.${parts[1]}.manage`)) return true;
      return false;
    };

    return { can, isAdmin, roles, permissions: perms };
  }, [me]);
}
