// PBI-79 / T-929: GET /api/products/:id/cross-sprint-blocks
//
// Lichte UX-hint voor disabled-vinkjes: welke stories binnen pbiIds zitten in
// een andere OPEN sprint (excludeSprintId expliciet uitgesloten). Server-side
// commit-actions blijven autoritatief — dit endpoint is alleen voor UI.
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 excludeSprintId = url.searchParams.get('excludeSprintId') ?? undefined
  const pbiIds = parsePbiIds(url.searchParams.get('pbiIds'))

  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 stories = await prisma.story.findMany({
    where: {
      pbi_id: { in: pbiIds },
      product_id: productId,
      sprint_id: { not: null },
      ...(excludeSprintId ? { NOT: { sprint_id: excludeSprintId } } : {}),
      sprint: { status: 'OPEN' },
    },
    select: {
      id: true,
      sprint: { select: { id: true, code: true } },
    },
  })

  const result: Record<string, { sprintId: string; sprintName: string }> = {}
  for (const story of stories) {
    if (!story.sprint) continue
    result[story.id] = {
      sprintId: story.sprint.id,
      sprintName: story.sprint.code,
    }
  }

  return Response.json(result)
}
