// PBI-74 / T-870: GET /api/stories/:id/tasks
//
// Levert tasks binnen een story voor ensureStoryLoaded. Access-control via
// product-eigenaarschap van de bovenliggende story.
import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
import { productAccessFilter } from '@/lib/product-access'
import { taskStatusToApi } 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 story = await prisma.story.findFirst({
    where: { id, product: productAccessFilter(auth.userId) },
    select: { id: true },
  })
  if (!story) {
    return Response.json({ error: 'Story niet gevonden' }, { status: 404 })
  }

  const tasks = await prisma.task.findMany({
    where: { story_id: id },
    orderBy: [{ sort_order: 'asc' }, { created_at: 'asc' }],
    select: {
      id: true,
      code: true,
      title: true,
      description: true,
      priority: true,
      sort_order: true,
      status: true,
      story_id: true,
      created_at: true,
    },
  })

  return Response.json(
    tasks.map((t) => ({ ...t, status: taskStatusToApi(t.status) })),
  )
}
