/**
 * API Route: Generate QR code data
 * GET /api/transport/qr/[id]
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getTransportChain } from '../../../../lib/transport/tracker';

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

  try {
    const { id, type } = req.query;

    if (!id || typeof id !== 'string') {
      return res.status(400).json({
        success: false,
        error: 'ID is required'
      });
    }

    const transportChain = getTransportChain();

    // Determine if this is a plant ID or batch ID
    const idType = type === 'batch' ? 'batch' : 'plant';

    const qrData = idType === 'batch'
      ? transportChain.generateQRData(undefined, id)
      : transportChain.generateQRData(id, undefined);

    res.status(200).json({
      success: true,
      data: {
        ...qrData,
        qrContent: JSON.stringify(qrData),
        scanUrl: qrData.quickLookupUrl
      }
    });
  } catch (error: any) {
    console.error('Error generating QR data:', error);
    res.status(500).json({ success: false, error: error.message || 'Internal server error' });
  }
}
