// PBI-74 / T-870: GET /api/products/:id/backlog
//
// Levert een volledige ProductBacklogSnapshot voor de workspace-store
// (ensureProductLoaded). Auth + access-control consistent met andere
// product-routes (authenticateApiRequest + productAccessFilter).
import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
import { productAccessFilter } from '@/lib/product-access'
import { pbiStatusToApi, storyStatusToApi, 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 product = await prisma.product.findFirst({
    where: { id, ...productAccessFilter(auth.userId) },
    select: { id: true, name: true },
  })
  if (!product) {
    return Response.json({ error: 'Product niet gevonden' }, { status: 404 })
  }

  const [pbis, stories, tasks] = await Promise.all([
    prisma.pbi.findMany({
      where: { product_id: id },
      orderBy: [{ priority: 'asc' }, { sort_order: 'asc' }, { created_at: 'asc' }],
      select: {
        id: true,
        code: true,
        title: true,
        priority: true,
        sort_order: true,
        description: true,
        created_at: true,
        status: true,
      },
    }),
    prisma.story.findMany({
      where: { product_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,
      },
    }),
    prisma.task.findMany({
      where: { story: { product_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,
      },
    }),
  ])

  const storiesByPbi: Record<string, unknown[]> = {}
  for (const story of stories) {
    const apiStory = { ...story, status: storyStatusToApi(story.status) }
    if (!storiesByPbi[story.pbi_id]) storiesByPbi[story.pbi_id] = []
    storiesByPbi[story.pbi_id].push(apiStory)
  }

  const tasksByStory: Record<string, unknown[]> = {}
  for (const task of tasks) {
    const apiTask = { ...task, status: taskStatusToApi(task.status) }
    if (!tasksByStory[task.story_id]) tasksByStory[task.story_id] = []
    tasksByStory[task.story_id].push(apiTask)
  }

  return Response.json({
    product,
    pbis: pbis.map((p) => ({ ...p, status: pbiStatusToApi(p.status) })),
    storiesByPbi,
    tasksByStory,
  })
}
