// API: Offers on a Listing
// GET /api/marketplace/listings/[id]/offers - Get all offers for a listing
// POST /api/marketplace/listings/[id]/offers - Create a new offer

import type { NextApiRequest, NextApiResponse } from 'next';
import { offerService, listingService } from '@/lib/marketplace';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { id: listingId } = req.query;

  if (!listingId || typeof listingId !== 'string') {
    return res.status(400).json({ error: 'Listing ID is required' });
  }

  try {
    switch (req.method) {
      case 'GET':
        return handleGet(listingId, req, res);
      case 'POST':
        return handlePost(listingId, req, res);
      default:
        res.setHeader('Allow', ['GET', 'POST']);
        return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
    }
  } catch (error) {
    console.error('Marketplace offers API error:', error);
    return res.status(500).json({
      error: 'Internal server error',
      message: error instanceof Error ? error.message : 'Unknown error',
    });
  }
}

async function handleGet(listingId: string, req: NextApiRequest, res: NextApiResponse) {
  const userId = req.headers['x-user-id'] as string;

  // Check if listing exists
  const listing = await listingService.getListingById(listingId);
  if (!listing) {
    return res.status(404).json({ error: 'Listing not found' });
  }

  // Only the seller can see all offers
  if (userId !== listing.sellerId) {
    return res.status(403).json({ error: 'Only the seller can view offers' });
  }

  const offers = await offerService.getOffersForListing(listingId);

  return res.status(200).json({
    listingId,
    offers,
    total: offers.length,
  });
}

async function handlePost(listingId: string, req: NextApiRequest, res: NextApiResponse) {
  const buyerId = req.headers['x-user-id'] as string || req.body.buyerId;
  const buyerName = req.headers['x-user-name'] as string || req.body.buyerName || 'Anonymous Buyer';

  if (!buyerId) {
    return res.status(401).json({ error: 'Authentication required' });
  }

  const { amount, message } = req.body;

  if (!amount || typeof amount !== 'number') {
    return res.status(400).json({ error: 'Offer amount is required' });
  }

  if (amount <= 0) {
    return res.status(400).json({ error: 'Offer amount must be greater than zero' });
  }

  try {
    const offer = await offerService.createOffer(buyerId, buyerName, {
      listingId,
      amount,
      message,
    });

    return res.status(201).json({
      success: true,
      offer,
    });
  } catch (error) {
    if (error instanceof Error) {
      return res.status(400).json({ error: error.message });
    }
    throw error;
  }
}
