import { NextResponse } from 'next/server';
import { getContent } from '@/content';
import { answerArchie } from '@/lib/archie';
import { decodeAnswers } from '@/lib/code';
import { paymentsMode, site } from '@/lib/config';

const MAX_MESSAGE_LENGTH = 500;

// Questions are answered and forgotten: nothing here is logged or stored.
export async function POST(request: Request) {
  const body = (await request.json().catch(() => null)) as { message?: unknown; resultCode?: unknown } | null;
  const message = typeof body?.message === 'string' ? body.message.trim() : '';
  if (!message) return NextResponse.json({ error: 'Please type a question.' }, { status: 400 });
  if (message.length > MAX_MESSAGE_LENGTH) {
    return NextResponse.json({ error: `Please keep questions under ${MAX_MESSAGE_LENGTH} characters.` }, { status: 400 });
  }

  const content = getContent();
  const resultCode =
    typeof body?.resultCode === 'string' && decodeAnswers(content.questions, body.resultCode) ? body.resultCode : undefined;

  const reply = answerArchie(message, {
    content,
    paymentsMode: paymentsMode(),
    supportEmail: site.supportEmail,
    resultCode,
  });
  return NextResponse.json({ reply });
}
