"use client";

import { useMutation, useQuery } from "@tanstack/react-query";

import { apiFetch } from "./api";
import type {
  AggregatedEstimate,
  TradeInEstimateInput,
} from "@/types/trade-in";

const BASE = "/api/v1/trade-in";

/**
 * POST /api/v1/trade-in/estimate
 * Sends apartment parameters and returns AggregatedEstimate (mock data for now).
 */
export function useEstimateMutation() {
  return useMutation<AggregatedEstimate, Error, TradeInEstimateInput>({
    mutationFn: (input) =>
      apiFetch<AggregatedEstimate>(`${BASE}/estimate`, {
        method: "POST",
        body: JSON.stringify(input),
      }),
  });
}

/**
 * GET /api/v1/trade-in/estimate/{id}
 * Fetches a previously computed estimate by UUID (for shareable links / PDF).
 */
export function useEstimate(estimate_id: string | null) {
  return useQuery<AggregatedEstimate>({
    queryKey: ["trade-in", "estimate", estimate_id],
    queryFn: () =>
      apiFetch<AggregatedEstimate>(`${BASE}/estimate/${estimate_id}`),
    enabled: estimate_id !== null && estimate_id.length > 0,
    staleTime: 10 * 60_000, // 10 min — estimates expire at expires_at anyway
  });
}
