import type { Endpoint } from 'payload'
import { assemble } from './assemble'

// GET /api/epc-content — one call returns the whole `window.EPC` overlay.
// Public (read-only). The front-end loader fetches this and merges it over the
// baked defaults. depth:1 populates upload fields so we can read media URLs.
export const epcContentEndpoint: Endpoint = {
  path: '/epc-content',
  method: 'get',
  handler: async (req) => {
    const { payload } = req
    const opts = { depth: 1, limit: 100, overrideAccess: true, pagination: false as const }

    const [markets, pricing, addons, pillars, cityScenes, product, images] = await Promise.all([
      payload.find({ collection: 'markets', ...opts }),
      payload.find({ collection: 'pricing', ...opts }),
      payload.find({ collection: 'addons', ...opts }),
      payload.find({ collection: 'pillars', ...opts }),
      payload.find({ collection: 'cityScenes', ...opts }),
      payload.findGlobal({ slug: 'product', depth: 1 }),
      payload.findGlobal({ slug: 'images', depth: 1 }),
    ])

    const data = assemble({
      markets: markets.docs, pricing: pricing.docs, addons: addons.docs,
      pillars: pillars.docs, cityScenes: cityScenes.docs, product, images,
    })

    return Response.json(data, {
      headers: {
        // CORS is also set globally in payload.config; this keeps the endpoint
        // robust if hit directly. CORS_ORIGINS env drives the allowed origin.
        'Access-Control-Allow-Origin': process.env.CORS_ORIGINS?.split(',')[0] || '*',
        'Cache-Control': 'public, max-age=30, stale-while-revalidate=300',
      },
    })
  },
}
