// PBI-79 / T-928: GET /api/products/:id/sprint-membership-summary
//
// Levert per PBI {total, inSprint} counts, gescoped op de doorgegeven pbiIds.
// Endpoint weigert product-brede aanroepen (pbiIds is verplicht). Eén groupBy
// + één count-by-sprint waar pbi_id IN (pbiIds).
import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
import { productAccessFilter } from '@/lib/product-access'

export const dynamic = 'force-dynamic'

function parsePbiIds(raw: string | null): string[] | null {
  if (!raw) return null
  const ids = raw
    .split(',')
    .map((s) => s.trim())
    .filter(Boolean)
  return ids.length === 0 ? null : ids
}

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: productId } = await params
  const url = new URL(request.url)
  const sprintId = url.searchParams.get('sprintId')
  const pbiIds = parsePbiIds(url.searchParams.get('pbiIds'))

  if (!sprintId) {
    return Response.json({ error: 'sprintId is verplicht' }, { status: 400 })
  }
  if (!pbiIds) {
    return Response.json(
      { error: 'pbiIds is verplicht (comma-separated)' },
      { status: 400 },
    )
  }

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

  const [totals, inSprint] = await Promise.all([
    prisma.story.groupBy({
      by: ['pbi_id'],
      where: { pbi_id: { in: pbiIds }, product_id: productId },
      _count: { _all: true },
    }),
    prisma.story.groupBy({
      by: ['pbi_id'],
      where: {
        pbi_id: { in: pbiIds },
        product_id: productId,
        sprint_id: sprintId,
      },
      _count: { _all: true },
    }),
  ])

  const inSprintByPbi = new Map<string, number>()
  for (const row of inSprint) {
    inSprintByPbi.set(row.pbi_id, row._count._all)
  }

  const result: Record<string, { total: number; inSprint: number }> = {}
  for (const pbiId of pbiIds) {
    result[pbiId] = { total: 0, inSprint: inSprintByPbi.get(pbiId) ?? 0 }
  }
  for (const row of totals) {
    result[row.pbi_id] = {
      total: row._count._all,
      inSprint: inSprintByPbi.get(row.pbi_id) ?? 0,
    }
  }

  return Response.json(result)
}
