import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { apiFetch } from "./client";
import type { RoutingRule } from "@/types/api";

interface ListPoliciesResponse {
  data: RoutingRule[];
}

export function useListPolicies() {
  return useQuery({
    queryKey: ["policies"],
    queryFn: () => apiFetch<ListPoliciesResponse>("/v1/admin/policies"),
    select: (d) => d.data,
  });
}

export function useGetPolicy(id: string) {
  return useQuery({
    queryKey: ["policies", id],
    queryFn: () => apiFetch<RoutingRule>(`/v1/admin/policies/${id}`),
    enabled: !!id,
  });
}

export interface PolicyPayload {
  name: string;
  description: string;
  priority: number;
  is_enabled: boolean;
  conditions: Array<{ field: string; operator: string; value: string }>;
  action: { provider: string; model: string; fallback_chain?: string[] };
}

export function useCreatePolicy() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (payload: PolicyPayload) =>
      apiFetch<RoutingRule>("/v1/admin/policies", {
        method: "POST",
        body: JSON.stringify(payload),
      }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["policies"] }),
  });
}

export function useUpdatePolicy() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, payload }: { id: string; payload: PolicyPayload }) =>
      apiFetch<RoutingRule>(`/v1/admin/policies/${id}`, {
        method: "PUT",
        body: JSON.stringify(payload),
      }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["policies"] }),
  });
}

export function useDeletePolicy() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) =>
      apiFetch<void>(`/v1/admin/policies/${id}`, { method: "DELETE" }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["policies"] }),
  });
}

export function useSeedTemplate() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (template: string) =>
      apiFetch<RoutingRule>(`/v1/admin/policies/seed/${template}`, { method: "POST" }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["policies"] }),
  });
}
