'use client';

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
  listReports,
  getReport,
  getReportStatus,
  generateReport,
  deleteReport,
  type ReportType,
} from '../reports-api';

export const reportKeys = {
  all: ['reports'] as const,
  list: (params?: { type?: ReportType; limit?: number; offset?: number }) =>
    ['reports', 'list', params] as const,
  detail: (id: string) => ['reports', 'detail', id] as const,
  status: (id: string) => ['reports', 'status', id] as const,
};

export function useReportsList(params?: {
  type?: ReportType;
  limit?: number;
  offset?: number;
}) {
  return useQuery({
    queryKey: reportKeys.list(params),
    queryFn: () => listReports(params),
  });
}

export function useReport(id: string | null) {
  return useQuery({
    queryKey: reportKeys.detail(id!),
    queryFn: () => getReport(id!),
    enabled: !!id,
  });
}

export function useReportStatus(id: string | null, shouldPoll = false) {
  return useQuery({
    queryKey: reportKeys.status(id!),
    queryFn: () => getReportStatus(id!),
    enabled: !!id,
    refetchInterval: shouldPoll ? 3000 : false,
  });
}

export function useGenerateReport() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: { type: ReportType; title: string; params: Record<string, unknown> }) =>
      generateReport(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: reportKeys.all });
    },
  });
}

export function useDeleteReport() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => deleteReport(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: reportKeys.all });
    },
  });
}
