// src/app/utils/postcodes.ts

export interface PostcodeLookupResult {
  status: number;
  result?: {
    postcode: string;
    country: string;
    region: string | null;
    admin_district: string | null;
    latitude: number;
    longitude: number;
  };
  error?: string;
}

/**
 * Look up a postcode using postcodes.io.
 * Includes automatic retry logic for transient 5xx errors.
 */
export async function lookupPostcode(
  postcode: string,
  retries = 2
): Promise<PostcodeLookupResult> {
  const url = `https://api.postcodes.io/postcodes/${encodeURIComponent(
    postcode.trim()
  )}`;

  for (let attempt = 0; attempt <= retries; attempt++) {
    try {
      const res = await fetch(url);

      if (!res.ok) {
        const data = await res.json();
        // Retry only on transient 5xx errors
        if (res.status >= 500 && attempt < retries) {
          console.warn(`Retrying postcode lookup (attempt ${attempt + 1})`);
          await new Promise((r) => setTimeout(r, 500 * (attempt + 1)));
          continue;
        }
        return data;
      }

      return await res.json();
    } catch (error) {
      if (attempt < retries) {
        console.warn(`Network error on attempt ${attempt + 1}, retrying...`);
        await new Promise((r) => setTimeout(r, 500 * (attempt + 1)));
      } else {
        return {
          status: 500,
          error: "Network error while contacting postcodes.io",
        };
      }
    }
  }

  // Should never reach here
  return { status: 500, error: "Unexpected error" };
}
