// app/(lib)/services/franchiseAddressesService.ts
import { apiClient } from "../../app/api/client";
import { handleAPIError } from "../utils/apiErrorHandler";

export interface FranchiseAddress {
  territory_country: string;
  territory_state: string;
  latitude: string;
  longitude: string;
}

export interface GlobeLocation {
  lat: number;
  lon: number;
  country?: string;
  state?: string;
}

export class FranchiseAddressesService {
  private readonly endpoint = "franchise-addresses/active-latlng";

  async fetchActiveFranchiseLocations(domain: string): Promise<GlobeLocation[]> {
    const startTime = Date.now();

    try {
      const response = await apiClient.get<FranchiseAddress[]>(
        this.endpoint,
        {
          headers: { "X-Domain": domain },
        }
      );

      if (!Array.isArray(response.data)) {
        return [];
      }

      // Transform API response to globe locations
      const locations: GlobeLocation[] = response.data
        .filter(address => address.latitude && address.longitude)
        .map(address => ({
          lat: parseFloat(address.latitude),
          lon: parseFloat(address.longitude),
          country: address.territory_country,
          state: address.territory_state,
        }))
        .filter(loc => !isNaN(loc.lat) && !isNaN(loc.lon));

      const elapsed = Date.now() - startTime;

      return locations;
    } catch (error) {
      return handleAPIError(
        error,
        domain,
        startTime,
        () => {
          console.error("[FranchiseAddressesService] Failed to fetch franchise addresses");
          return [];
        }
      );
    }
  }
}

export const franchiseAddressesService = new FranchiseAddressesService();
