/**
 * Address Service
 *
 * Handles address lookup API calls using Japan Post ZIP code lookup.
 * Hooks should use this service instead of calling the API directly.
 */

import { apiClient, getDataOrThrow } from "@/core/api";
import {
  type AddressLookupResult,
  addressLookupResultSchema,
} from "@customer-portal/domain/address";

// ============================================================================
// Constants
// ============================================================================

const EMPTY_LOOKUP_RESULT: AddressLookupResult = {
  zipCode: "",
  addresses: [],
  count: 0,
};

// ============================================================================
// API Functions
// ============================================================================

/**
 * Lookup address by ZIP code using Japan Post API
 *
 * @param zipCode - Japanese ZIP code (e.g., "100-0001" or "1000001")
 * @returns Address lookup result with Japanese and romanized address data
 */
async function lookupByZipCode(zipCode: string): Promise<AddressLookupResult> {
  // Normalize ZIP code (remove hyphen if present)
  const normalizedZip = zipCode.replace(/-/g, "");

  const response = await apiClient.GET<AddressLookupResult>("/api/address/lookup/zip/{zipCode}", {
    params: { path: { zipCode: normalizedZip } },
  });

  const data = getDataOrThrow(response, "ZIP code lookup failed");
  return addressLookupResultSchema.parse(data);
}

/**
 * Check if address lookup service is available
 *
 * @returns Service availability status
 */
async function getStatus(): Promise<{ available: boolean }> {
  const response = await apiClient.GET<{ available: boolean }>("/api/address/status");
  return getDataOrThrow(response, "Failed to check address service status");
}

// ============================================================================
// Service Export
// ============================================================================

export const addressService = {
  lookupByZipCode,
  getStatus,
} as const;

// Re-export constants for use in hooks
export { EMPTY_LOOKUP_RESULT };
