// API: My Listings
// GET /api/marketplace/my-listings - Get current user's listings

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

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'GET') {
    res.setHeader('Allow', ['GET']);
    return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
  }

  try {
    const sellerId = req.headers['x-user-id'] as string;

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

    const { status } = req.query;

    let listings = await listingService.getListingsBySeller(sellerId);

    // Filter by status if provided
    if (status && typeof status === 'string') {
      listings = listings.filter(l => l.status === status as ListingStatus);
    }

    // Get statistics
    const stats = await listingService.getSellerStats(sellerId);

    // Sort by most recent first
    listings.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());

    return res.status(200).json({
      listings,
      total: listings.length,
      stats,
    });
  } catch (error) {
    console.error('My listings API error:', error);
    return res.status(500).json({
      error: 'Internal server error',
      message: error instanceof Error ? error.message : 'Unknown error',
    });
  }
}
