// API: Featured Listings
// GET /api/marketplace/featured - Get featured and recent listings

import type { NextApiRequest, NextApiResponse } from 'next';
import { searchService } from '@/lib/marketplace';
import type { ListingCategory } 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 { category, limit: limitParam } = req.query;
    const limit = limitParam ? parseInt(limitParam as string, 10) : 6;

    // Get featured listings
    const featured = await searchService.getFeaturedListings(limit);

    // Get recent listings
    const recent = await searchService.getRecentListings(limit);

    // Get category-specific listings if requested
    let categoryListings = null;
    if (category && typeof category === 'string') {
      categoryListings = await searchService.getListingsByCategory(
        category as ListingCategory,
        limit
      );
    }

    // Get marketplace stats
    const stats = await searchService.getMarketplaceStats();

    // Get popular tags
    const popularTags = await searchService.getPopularTags(15);

    return res.status(200).json({
      featured,
      recent,
      categoryListings,
      stats,
      popularTags,
    });
  } catch (error) {
    console.error('Featured listings API error:', error);
    return res.status(500).json({
      error: 'Internal server error',
      message: error instanceof Error ? error.message : 'Unknown error',
    });
  }
}
