// PBI-74 / T-870: GET /api/pbis/:id/stories
//
// Levert stories binnen een PBI voor ensurePbiLoaded. Access-control via
// product-eigenaarschap van het bovenliggende PBI.
import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
import { productAccessFilter } from '@/lib/product-access'
import { storyStatusToApi } from '@/lib/task-status'

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 pbi = await prisma.pbi.findFirst({
    where: { id, product: productAccessFilter(auth.userId) },
    select: { id: true },
  })
  if (!pbi) {
    return Response.json({ error: 'PBI niet gevonden' }, { status: 404 })
  }

  const stories = await prisma.story.findMany({
    where: { pbi_id: id },
    orderBy: [{ sort_order: 'asc' }, { created_at: 'asc' }],
    select: {
      id: true,
      code: true,
      title: true,
      description: true,
      acceptance_criteria: true,
      priority: true,
      sort_order: true,
      status: true,
      pbi_id: true,
      sprint_id: true,
      created_at: true,
    },
  })

  return Response.json(
    stories.map((s) => ({ ...s, status: storyStatusToApi(s.status) })),
  )
}
