import { NextRequest } from 'next/server'
import { findTask, taskEvents, updateTask } from '@/lib/data/dev-tasks'
import { devTaskUpdateSchema } from '@/lib/domain/dev-tasks'
import { noStore, sessionActor } from '@/lib/integrations/dev-task-auth'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'

type Ctx = { params: Promise<{ ref: string }> }

/** The board page: one task's history and comments. */
export async function GET(_req: NextRequest, ctx: Ctx) {
  const auth = await sessionActor()
  if (!auth.ok) return auth.response
  const found = await findTask((await ctx.params).ref)
  if (!found.ok) return noStore({ error: found.error }, found.status)
  return noStore({ task: found.value, events: await taskEvents(found.value.id) })
}

/** The board page: the developer moves a task; the admin may also reorder, edit or remove. */
export async function PATCH(req: NextRequest, ctx: Ctx) {
  const auth = await sessionActor()
  if (!auth.ok) return auth.response
  let json: unknown
  try { json = await req.json() } catch { return noStore({ error: 'Invalid JSON.' }, 400) }
  const parsed = devTaskUpdateSchema.safeParse(json)
  if (!parsed.success) return noStore({ error: 'Invalid update.' }, 400)
  const result = await updateTask((await ctx.params).ref, parsed.data, auth.actor)
  return result.ok ? noStore({ task: result.value }) : noStore({ error: result.error }, result.status)
}
