import type { NextApiRequest, NextApiResponse } from 'next';
import { getPickupPoints } from '../../../lib/packeta';

interface LocationResponse {
  locations?: Array<{
    id: string | number;
    name: string;
    city: string;
    street: string;
    zip: string;
    country: string;
    latitude?: number;
    longitude?: number;
  }>;
  error?: string;
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<LocationResponse>
) {
  if (req.method !== 'GET') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const { zip, country = 'CZ' } = req.query;

    // Validate postal code if provided
    if (zip && typeof zip !== 'string') {
      return res.status(400).json({ error: 'Invalid postal code parameter' });
    }

    const locations = await getPickupPoints(
      zip as string | undefined,
      country as string
    );

    // Remove carrierName from response (internal use only)
    const cleanedLocations = locations.map((loc) => ({
      id: loc.id,
      name: loc.name,
      city: loc.city,
      street: loc.street,
      zip: loc.zip,
      country: loc.country,
      latitude: loc.latitude,
      longitude: loc.longitude,
    }));

    return res.status(200).json({ locations: cleanedLocations });
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : 'Failed to fetch locations';
    return res.status(500).json({ error: errorMessage });
  }
}
