// API: Single Marketplace Listing
// GET /api/marketplace/listings/[id] - Get a listing
// PUT /api/marketplace/listings/[id] - Update a listing
// DELETE /api/marketplace/listings/[id] - Delete a listing

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

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

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

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

async function handleGet(id: string, res: NextApiResponse) {
  const listing = await listingService.viewListing(id);

  if (!listing) {
    return res.status(404).json({ error: 'Listing not found' });
  }

  return res.status(200).json(listing);
}

async function handlePut(id: string, req: NextApiRequest, res: NextApiResponse) {
  const sellerId = req.headers['x-user-id'] as string || req.body.sellerId;

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

  const updates: UpdateListingInput = {};

  if (req.body.title) updates.title = req.body.title;
  if (req.body.description) updates.description = req.body.description;
  if (req.body.price) updates.price = parseFloat(req.body.price);
  if (req.body.quantity) updates.quantity = parseInt(req.body.quantity, 10);
  if (req.body.status) updates.status = req.body.status;
  if (req.body.tags) updates.tags = req.body.tags;
  if (req.body.expiresAt) updates.expiresAt = new Date(req.body.expiresAt);

  try {
    const listing = await listingService.updateListing(id, sellerId, updates);

    if (!listing) {
      return res.status(404).json({ error: 'Listing not found' });
    }

    return res.status(200).json({
      success: true,
      listing,
    });
  } catch (error) {
    if (error instanceof Error && error.message.includes('Unauthorized')) {
      return res.status(403).json({ error: error.message });
    }
    throw error;
  }
}

async function handleDelete(id: string, req: NextApiRequest, res: NextApiResponse) {
  const sellerId = req.headers['x-user-id'] as string || req.body.sellerId;

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

  try {
    const deleted = await listingService.deleteListing(id, sellerId);

    if (!deleted) {
      return res.status(404).json({ error: 'Listing not found' });
    }

    return res.status(200).json({
      success: true,
      message: 'Listing deleted successfully',
    });
  } catch (error) {
    if (error instanceof Error) {
      if (error.message.includes('Unauthorized')) {
        return res.status(403).json({ error: error.message });
      }
      if (error.message.includes('Cannot delete')) {
        return res.status(400).json({ error: error.message });
      }
    }
    throw error;
  }
}
