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

interface RateResponse {
  rates?: Array<{
    service: string;
    price: number;
    days: number;
  }>;
  error?: string;
}

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

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

    // Validate required parameters
    if (!zip || typeof zip !== 'string') {
      return res.status(400).json({ error: 'Postal code is required' });
    }

    const weightNum = parseFloat(weight as string) || 1;

    const rates = await getShippingRate(
      zip,
      weightNum,
      country as string
    );

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