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

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

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

/** One task with its full history and comments. `ref` is T-12, 12 or the id. */
export async function GET(req: NextRequest, ctx: Ctx) {
  const auth = apiActor(req)
  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) })
}

/** Edit the brief, move it, place it ({ place: { before | after: <id> } | { edge: top | bottom } }), remove or restore it. */
export async function PATCH(req: NextRequest, ctx: Ctx) {
  const auth = apiActor(req)
  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.', issues: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`) }, 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)
}

/** Remove a task from the board. It is kept (archived) with its history and can be restored. */
export async function DELETE(req: NextRequest, ctx: Ctx) {
  const auth = apiActor(req)
  if (!auth.ok) return auth.response
  const result = await updateTask((await ctx.params).ref, { archived: true }, auth.actor)
  return result.ok ? noStore({ task: result.value }) : noStore({ error: result.error }, result.status)
}
