import { apiRoute } from '@/lib/api/handler'
import { listDiscoveries, listDiscoveryRuns } from '@/lib/services/discovery-service'

export const dynamic = 'force-dynamic'

/** Discovered scenarios and the runs that produced them (§19, §21, §22). */
export const GET = apiRoute({ permission: 'discovery.read' }, async ({ searchParams }) => {
  const limit = Math.min(50, Math.max(1, Number(searchParams.get('limit')) || 20))
  const status = searchParams.get('status') ?? undefined

  const [discoveries, runs] = await Promise.all([
    listDiscoveries({ limit, status }),
    listDiscoveryRuns(10),
  ])

  return {
    discoveries,
    runs: runs.map((run) => ({ ...run, createdAt: run.createdAt.getTime() })),
  }
})
