import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
import { productAccessFilter } from '@/lib/product-access'
import { taskStatusToApi } from '@/lib/task-status'

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 url = new URL(request.url)
  const limitParam = parseInt(url.searchParams.get('limit') ?? '10')
  const limit = Math.min(Math.max(1, limitParam), 50)

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

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

  const enriched = tasks.map((t) => {
    const positionInStory = t.story.tasks.findIndex((st) => st.id === t.id)
    const code = t.story.code && positionInStory >= 0 ? `${t.story.code}.${positionInStory + 1}` : null
    return {
      id: t.id,
      code,
      title: t.title,
      description: t.description,
      implementation_plan: t.implementation_plan,
      story_id: t.story_id,
      story_code: t.story.code,
      priority: t.priority,
      sort_order: t.sort_order,
      status: taskStatusToApi(t.status),
    }
  })

  return Response.json(enriched)
}
