"use client";

import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslationStore } from "@/lib/store";
import { API_BASE } from "@/lib/config";
import type { CleanupResponse } from "./types";
import { QUERY_KEY as DASHBOARD_QUERY_KEY } from "./useAdminDashboard";

const TIMEOUT_MS = 15000;

async function triggerCleanupApi(adminToken: string | null | undefined): Promise<CleanupResponse> {
  if (!adminToken) {
    throw new Error("AUTH_REQUIRED");
  }

  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS);

  try {
    const response = await fetch(`${API_BASE}/api/v1/admin/cleanup/trigger`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${adminToken}`,
      },
      signal: controller.signal,
    });

    clearTimeout(timeoutId);

    if (!response.ok) {
      if (response.status === 401) {
        throw new Error("UNAUTHORIZED");
      }
      throw new Error(`HTTP_ERROR_${response.status}`);
    }

    return await response.json();
  } catch (err) {
    clearTimeout(timeoutId);
    throw err;
  }
}

export function useCleanup() {
  const { settings } = useTranslationStore();
  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: () => triggerCleanupApi(settings.adminToken),
    onSuccess: () => {
      // Invalidate dashboard cache after successful cleanup
      queryClient.invalidateQueries({ queryKey: DASHBOARD_QUERY_KEY });
    },
  });

  // Map error codes to user-friendly messages
  const getErrorMessage = (err: Error | null): string | null => {
    if (!err) return null;
    
    const errorMap: Record<string, string> = {
      AUTH_REQUIRED: "Veuillez vous connecter pour effectuer cette action",
      UNAUTHORIZED: "Session expirée. Veuillez vous reconnecter.",
      HTTP_ERROR_403: "Accès refusé. Droits administrateur requis.",
      HTTP_ERROR_500: "Erreur serveur lors du nettoyage. Veuillez réessayer.",
    };

    const code = err.message;
    if (errorMap[code]) {
      return errorMap[code];
    }
    
    if (err.name === "AbortError") {
      return "Le serveur met trop de temps à répondre. Veuillez réessayer.";
    }
    
    return "Erreur lors du nettoyage. Veuillez réessayer.";
  };

  const errorMessage = mutation.error ? getErrorMessage(mutation.error as Error) : null;

  return {
    isPurging: mutation.isPending,
    purgeResult: mutation.data ?? null,
    error: errorMessage,
    triggerCleanup: mutation.mutateAsync,
  };
}
