const PACKETA_BASE_URL = process.env.PACKETA_BASE_URL || 'https://api.packeta.com';
const PACKETA_API_KEY = process.env.PACKETA_API_KEY;


interface PacketaPickupPoint {
  id: string | number;
  name: string;
  city: string;
  street: string;
  zip: string;
  country: string;
  latitude?: number;
  longitude?: number;
  openingHours?: string;
  carrierName: string;
}

async function makeRequest(
  endpoint: string,
  method: 'GET' | 'POST' | 'PUT' | 'DELETE' = 'GET',
  body?: Record<string, any>,
  headers?: Record<string, string>
): Promise<any> {
  if (!PACKETA_API_KEY) {
    throw new Error('PACKETA_API_KEY environment variable is not set');
  }

  const url = `${PACKETA_BASE_URL}${endpoint}`;
  
  const requestOptions: RequestInit = {
    method,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${PACKETA_API_KEY}`,
      ...headers,
    },
  };

  if (body) {
    requestOptions.body = JSON.stringify(body);
  }

  try {
    const response = await fetch(url, requestOptions);

    if (!response.ok) {
      const error = await response.json().catch(() => ({ message: response.statusText }));
      throw new Error(`Packeta API error (${response.status}): ${JSON.stringify(error)}`);
    }

    return await response.json();
  } catch (error) {
    throw error;
  }
}

export async function getPickupPoints(
  zip?: string,
  country: string = 'CZ'
): Promise<PacketaPickupPoint[]> {
  try {
    const params = new URLSearchParams({
      country,
      ...(zip && { zip }),
      limit: '100',
    });

    const response = await makeRequest(`/v1/branch?${params.toString()}`);
    
    // Packeta returns array of pickup points
    if (!Array.isArray(response)) {
      return [];
    }

    return response.map((point: any) => ({
      id: point.id,
      name: point.name,
      city: point.city,
      street: point.street,
      zip: point.zip,
      country: point.country,
      latitude: point.latitude,
      longitude: point.longitude,
      carrierName: 'packeta',
    }));
  } catch (error) {
    throw error;
  }
}

export async function getShippingRate(
  zip: string,
  weight: number = 1,
  country: string = 'CZ'
): Promise<Array<{ service: string; price: number; days: number }>> {
  try {
    const params = new URLSearchParams({
      country,
      zip,
      weight: weight.toString(),
    });

    const response = await makeRequest(`/v1/rates?${params.toString()}`);

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

    return response.map((rate: any) => ({
      service: rate.service,
      price: rate.price,
      days: rate.deliveryDays,
    }));
  } catch (error) {
    throw error;
  }
}
