import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
import { productAccessFilter } from '@/lib/product-access'
import { storyStatusToApi, 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 sprint = await prisma.sprint.findFirst({
    where: { product_id: id, status: 'OPEN', product: productAccessFilter(auth.userId) },
  })
  if (!sprint) {
    return Response.json({ error: 'Geen actieve Sprint gevonden' }, { status: 404 })
  }

  const story = await prisma.story.findFirst({
    where: { sprint_id: sprint.id, status: 'IN_SPRINT' },
    orderBy: [{ sort_order: 'asc' }],
    include: {
      tasks: {
        orderBy: { sort_order: 'asc' },
        select: {
          id: true,
          title: true,
          description: true,
          implementation_plan: true,
          priority: true,
          sort_order: true,
          status: true,
        },
      },
    },
  })

  if (!story) {
    return Response.json({ error: 'Geen open stories in de Sprint' }, { status: 404 })
  }

  const tasks = story.tasks.map((t, idx) => ({
    id: t.id,
    code: story.code ? `${story.code}.${idx + 1}` : null,
    title: t.title,
    description: t.description,
    implementation_plan: t.implementation_plan,
    priority: t.priority,
    sort_order: t.sort_order,
    status: taskStatusToApi(t.status),
  }))

  return Response.json({
    id: story.id,
    code: story.code,
    title: story.title,
    description: story.description,
    acceptance_criteria: story.acceptance_criteria,
    status: storyStatusToApi(story.status),
    tasks,
  })
}
