import { NextRequest } from 'next/server'
import { addComment } from '@/lib/data/dev-tasks'
import { devTaskCommentSchema } from '@/lib/domain/dev-tasks'
import { apiActor, noStore } from '@/lib/integrations/dev-task-auth'

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

/** A comment on a task: the CTO's answer or note, shown on the card for the developer. */
export async function POST(req: NextRequest, ctx: { params: Promise<{ ref: string }> }) {
  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 = devTaskCommentSchema.safeParse(json)
  if (!parsed.success) return noStore({ error: 'A comment needs text (up to 4000 characters).' }, 400)
  const result = await addComment((await ctx.params).ref, parsed.data.text, auth.actor)
  return result.ok ? noStore({ comment: result.value }, 201) : noStore({ error: result.error }, result.status)
}
