import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { adminFetch } from './admin-api';

// ── Types ──────────────────────────────────────────────────────────────

export interface ClaimMappingRule {
  id: string;
  claim: string;
  matchType: 'equals' | 'contains' | 'regex';
  matchValue: string;
  action: 'assignRole' | 'addToGroup';
  target: string;
  priority: number;
  createdAt: string;
}

export interface CreateRuleRequest {
  claim: string;
  matchType: string;
  matchValue: string;
  action: string;
  target: string;
  priority: number;
}

export interface MatchedRuleResponse {
  ruleId: string;
  priority: number;
  claim: string;
  matchType: string;
  matchValue: string;
  action: string;
  target: string;
}

export interface TestResponse {
  matchedRules: MatchedRuleResponse[];
  effectiveRoles: string[];
  effectiveGroups: string[];
  fallback: boolean;
}

// ── Query Hooks ────────────────────────────────────────────────────────

export function useClaimMappingRules() {
  return useQuery({
    queryKey: ['admin', 'claim-mappings'],
    queryFn: () => adminFetch<ClaimMappingRule[]>('/claim-mappings'),
  });
}

// ── Mutation Hooks ─────────────────────────────────────────────────────

export function useCreateClaimMappingRule() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (req: CreateRuleRequest) =>
      adminFetch<ClaimMappingRule>('/claim-mappings', {
        method: 'POST',
        body: JSON.stringify(req),
      }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['admin', 'claim-mappings'] });
    },
  });
}

export function useUpdateClaimMappingRule() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, ...req }: CreateRuleRequest & { id: string }) =>
      adminFetch<ClaimMappingRule>(`/claim-mappings/${id}`, {
        method: 'PUT',
        body: JSON.stringify(req),
      }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['admin', 'claim-mappings'] });
    },
  });
}

export function useDeleteClaimMappingRule() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) =>
      adminFetch<void>(`/claim-mappings/${id}`, { method: 'DELETE' }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['admin', 'claim-mappings'] });
    },
  });
}

export interface TestRuleInput {
  id: string;
  claim: string;
  matchType: string;
  matchValue: string;
  action: string;
  target: string;
  priority: number;
}

export function useTestClaimMappingRules() {
  return useMutation({
    mutationFn: ({ rules, claims }: { rules: TestRuleInput[]; claims: Record<string, unknown> }) =>
      adminFetch<TestResponse>('/claim-mappings/test', {
        method: 'POST',
        body: JSON.stringify({ rules, claims }),
      }),
  });
}
