import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  ManagerDashboardSchema,
  EquipeResponseSchema,
  AlcadaDescontosResponseSchema,
  PromocoesResponseSchema,
  RegrasDescontoResponseSchema,
  GruposProdutoResponseSchema,
  type ManagerDashboard,
  type EquipeResponse,
  type AlcadaDescontosResponse,
  type PromocoesResponse,
  type UpsertDescontoBody,
  type CreatePromocaoBody,
  type UpdatePromocaoBody,
  type RegrasDescontoResponse,
  type GruposProdutoResponse,
  type CreateRegraDescontoBody,
  type UpdateRegraDescontoBody,
} from '@sar/api-interface';
import { apiFetch } from '../api-client';

export function useManagerDashboard(mes?: number, ano?: number) {
  const params = new URLSearchParams();
  if (mes) params.set('mes', String(mes));
  if (ano) params.set('ano', String(ano));
  const qs = params.size > 0 ? `?${params.toString()}` : '';
  return useQuery<ManagerDashboard>({
    queryKey: ['dashboard', 'manager', mes, ano],
    queryFn: async () => {
      const raw = await apiFetch(`/dashboard/manager${qs}`);
      return ManagerDashboardSchema.parse(raw);
    },
    staleTime: 60 * 1000,
    refetchInterval: 60 * 1000,
  });
}

export function useEquipe() {
  return useQuery<EquipeResponse>({
    queryKey: ['equipe'],
    queryFn: async () => {
      const raw = await apiFetch('/equipe');
      return EquipeResponseSchema.parse(raw);
    },
    staleTime: 5 * 60 * 1000,
  });
}

export function usePoliticasDescontos() {
  return useQuery<AlcadaDescontosResponse>({
    queryKey: ['politicas', 'descontos'],
    queryFn: async () => {
      const raw = await apiFetch('/politicas/descontos');
      return AlcadaDescontosResponseSchema.parse(raw);
    },
    staleTime: 10 * 60 * 1000,
  });
}

export function usePromocoes() {
  return useQuery<PromocoesResponse>({
    queryKey: ['politicas', 'promocoes'],
    queryFn: async () => {
      const raw = await apiFetch('/politicas/promocoes');
      return PromocoesResponseSchema.parse(raw);
    },
    staleTime: 5 * 60 * 1000,
  });
}

export function useUpsertDesconto() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (body: UpsertDescontoBody) =>
      apiFetch('/politicas/descontos', { method: 'POST', body }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['politicas', 'descontos'] }),
  });
}

export function useCreatePromocao() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (body: CreatePromocaoBody) =>
      apiFetch('/politicas/promocoes', { method: 'POST', body }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['politicas', 'promocoes'] });
      qc.invalidateQueries({ queryKey: ['dashboard', 'manager'] });
    },
  });
}

export function useUpdatePromocao() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, body }: { id: number; body: UpdatePromocaoBody }) =>
      apiFetch(`/politicas/promocoes/${id}`, { method: 'PATCH', body }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['politicas', 'promocoes'] });
      qc.invalidateQueries({ queryKey: ['dashboard', 'manager'] });
    },
  });
}

export function useDeletePromocao() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => apiFetch(`/politicas/promocoes/${id}`, { method: 'DELETE' }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['politicas', 'promocoes'] });
      qc.invalidateQueries({ queryKey: ['dashboard', 'manager'] });
    },
  });
}

export function useRegrasDesconto() {
  return useQuery<RegrasDescontoResponse>({
    queryKey: ['politicas', 'regras'],
    queryFn: async () => {
      const raw = await apiFetch('/politicas/regras');
      return RegrasDescontoResponseSchema.parse(raw);
    },
    staleTime: 5 * 60 * 1000,
  });
}

export function useGruposProduto() {
  return useQuery<GruposProdutoResponse>({
    queryKey: ['politicas', 'grupos-produto'],
    queryFn: async () => {
      const raw = await apiFetch('/politicas/grupos-produto');
      return GruposProdutoResponseSchema.parse(raw);
    },
    staleTime: 30 * 60 * 1000,
  });
}

export function useCreateRegraDesconto() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (body: CreateRegraDescontoBody) =>
      apiFetch('/politicas/regras', { method: 'POST', body }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['politicas', 'regras'] });
      qc.invalidateQueries({ queryKey: ['politicas', 'regras-vigentes'] });
    },
  });
}

export function useUpdateRegraDesconto() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, body }: { id: number; body: UpdateRegraDescontoBody }) =>
      apiFetch(`/politicas/regras/${id}`, { method: 'PATCH', body }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['politicas', 'regras'] });
      qc.invalidateQueries({ queryKey: ['politicas', 'regras-vigentes'] });
    },
  });
}

export function useDeleteRegraDesconto() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => apiFetch(`/politicas/regras/${id}`, { method: 'DELETE' }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['politicas', 'regras'] });
      qc.invalidateQueries({ queryKey: ['politicas', 'regras-vigentes'] });
    },
  });
}
