"use client";

import { useAuth, type Role } from "@/lib/auth-context";
import { type ReactNode } from "react";

type ActionGuardProps = {
  allowedRoles: Role[];
  /** Jika true, hanya tampilkan jika user login sama dengan owner row */
  ownRowOnly?: boolean;
  /** ID pemilik row (misal approver_id) — jika ownRowOnly=true, harus diisi */
  ownerId?: string;
  /** Fallback jika tidak punya akses — default: null (sembunyi) */
  fallback?: ReactNode;
  children: ReactNode;
};

export function ActionGuard({
  allowedRoles,
  ownRowOnly,
  ownerId,
  fallback = null,
  children,
}: ActionGuardProps) {
  const { hasRole, session } = useAuth();

  if (!session) return <>{fallback}</>;
  if (!hasRole(...allowedRoles)) return <>{fallback}</>;
  if (ownRowOnly && (!ownerId || session.user.id !== ownerId)) return <>{fallback}</>;

  return <>{children}</>;
}
