"use client";

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

export interface PostcodeResult {
  postcode: string;
  country: string;
  region: string | null;
  admin_district: string | null;
  latitude: number;
  longitude: number;
}

export interface PostcodeLookupResponse {
  status: number;
  result: PostcodeResult | null;
  message?: string;
}

/**
 * Calls your /api/postcode/:postcode endpoint.
 * Handles 404 gracefully (invalid postcode),
 * 500 gracefully (external service issue),
 * and only throws on client-side misuse (400).
 */
async function fetchPostcode(
  postcode: string
): Promise<PostcodeLookupResponse> {
  const res = await fetch(`/api/postcode/${encodeURIComponent(postcode)}`);
  const data = await res.json();

  switch (res.status) {
    case 200:
      return { status: 200, result: data.result };
    case 404:
      // Invalid postcode (user input issue)
      return { status: 404, result: null, message: "Invalid postcode" };
    case 500:
      // External API error
      return {
        status: 500,
        result: null,
        message:
          "We're having trouble reaching the postcode service. Please try again later.",
      };
    case 400:
      // Bad query from our side (should not happen in production)
      throw new Error("Postcode API query malformed (400).");
    default:
      // Unexpected case
      return {
        status: res.status,
        result: null,
        message: data.error || "Unexpected response from postcode API",
      };
  }
}

/**
 * React Query hook for postcode validation and lookup
 */
function usePostcodeLookup(postcode: string, shouldFetch: boolean) {
  return useQuery({
    queryKey: ["postcode-lookup", postcode],
    queryFn: () => fetchPostcode(postcode),
    enabled: shouldFetch && !!postcode,
    retry: false,
    staleTime: 1000 * 60 * 5,
  });
}

export default usePostcodeLookup;
