'use client';
import { useQuery } from '@tanstack/react-query';
import { api } from './api';
import { useAuth } from './auth-context';

export type PermModule = 'deviation' | 'capa' | 'sample';
export type PermAction = 'view' | 'create' | 'update' | 'delete';

const COL: Record<PermAction, string> = {
  view: 'can_view', create: 'can_create', update: 'can_update', delete: 'can_delete',
};

/** Legacy defaults (used while loading or when no matrix row exists). */
function legacy(role: string, action: PermAction): boolean {
  if (role === 'super_admin' || role === 'admin' || role === 'stakeholder') return true;
  return action === 'view' || action === 'update';
}

/**
 * Can the signed-in user perform `action` on `module`?
 * Server is the source of truth (every endpoint re-checks); this just
 * hides/shows buttons. Defaults to legacy behaviour while loading.
 */
export function useCan(module: PermModule, action: PermAction): boolean {
  const { user } = useAuth();
  const q = useQuery({
    queryKey: ['role-perms'], queryFn: () => api.get('/api/v1/role-permissions'),
    enabled: !!user && (user.role === 'stakeholder' || user.role === 'employee'),
    staleTime: 5 * 60 * 1000, retry: false,
  });
  if (!user) return false;
  if (user.role === 'super_admin' || user.role === 'admin') return true;
  const rows: any[] = q.data ?? [];
  const row = rows.find((r) => r.role === user.role && r.module === module);
  if (!row) return legacy(user.role, action);
  return !!row[COL[action]];
}
