// PBI-74 / Story 9 / T-882: GET /api/products/:id/sprints
//
// Levert een lijst sprints voor een product (sprint-workspace
// ensureProductSprintsLoaded). Auth + access-control consistent met andere
// product-routes.

import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
import { productAccessFilter } from '@/lib/product-access'

export const dynamic = 'force-dynamic'

export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const auth = await authenticateApiRequest(request)
  if ('error' in auth) {
    return Response.json({ error: auth.error }, { status: auth.status })
  }

  const { id } = await params

  const product = await prisma.product.findFirst({
    where: { id, ...productAccessFilter(auth.userId) },
    select: { id: true },
  })
  if (!product) {
    return Response.json({ error: 'Product niet gevonden' }, { status: 404 })
  }

  const sprints = await prisma.sprint.findMany({
    where: { product_id: id },
    orderBy: [
      { status: 'asc' }, // OPEN < CLOSED alfabetisch — workspace-store her-sorteert
      { start_date: 'desc' },
      { created_at: 'desc' },
    ],
    select: {
      id: true,
      product_id: true,
      code: true,
      sprint_goal: true,
      status: true,
      start_date: true,
      end_date: true,
      created_at: true,
      completed_at: true,
    },
  })

  return Response.json(
    sprints.map((s) => ({
      ...s,
      start_date: s.start_date ? s.start_date.toISOString().slice(0, 10) : null,
      end_date: s.end_date ? s.end_date.toISOString().slice(0, 10) : null,
    })),
  )
}
