/**
 * Public marketplace catalog — published products only (no auth).
 */
import type { FastifyInstance } from 'fastify'
import { catalogService } from '../services/catalog.js'
import type { Context } from '../types/context.js'

function publicContext(): Context {
  return {
    request: {} as Context['request'],
    user: undefined,
    tenantContext: undefined,
    db: undefined as unknown as Context['db'],
  }
}

export async function registerMarketplacePublicRoutes(fastify: FastifyInstance) {
  fastify.get('/api/v1/marketplace/products', async (request, reply) => {
    const q = request.query as { category?: string; search?: string; featured?: string; limit?: string }
    const filter = {
      ...(q.category && { category: q.category }),
      ...(q.search && { search: q.search }),
      ...(q.featured === 'true' && { featured: true }),
      ...(q.limit && { limit: Math.min(Number(q.limit) || 50, 100) }),
    }
    const products = await catalogService.getProducts(publicContext(), filter)
    return reply.send({ products, count: products.length })
  })

  fastify.get('/api/v1/marketplace/products/:slug', async (request, reply) => {
    const { slug } = request.params as { slug: string }
    const product = await catalogService.getProductBySlug(publicContext(), slug)
    if (!product || product.status !== 'PUBLISHED') {
      return reply.code(404).send({ error: 'Product not found', slug })
    }
    return reply.send({ product })
  })
}
