import { NextResponse } from 'next/server';
import { AnonymousStoreError, addAnonymousRecord } from '@/lib/anonymous-store';
import { EncryptedAssessmentRecord } from '@/lib/assessment-types';

export const runtime = 'nodejs';

function errorResponse(error: unknown) {
  if (error instanceof AnonymousStoreError) {
    return NextResponse.json({ error: error.message }, { status: error.status });
  }
  console.error(error);
  return NextResponse.json({ error: '匿名档案服务暂时不可用' }, { status: 500 });
}

export async function POST(request: Request) {
  try {
    const body = await request.json().catch(() => ({}));
    const encryptedRecord = body.encryptedRecord as EncryptedAssessmentRecord | undefined;
    if (
      !encryptedRecord?.questionnaireId ||
      encryptedRecord.encrypted !== true ||
      encryptedRecord.payload?.format !== 'mindscope-encrypted-record'
    ) {
      return NextResponse.json({ error: '加密测评记录格式不完整' }, { status: 400 });
    }
    const saved = await addAnonymousRecord(
      String(body.codeName || ''),
      String(body.password || ''),
      encryptedRecord,
    );
    return NextResponse.json({ record: saved });
  } catch (error) {
    return errorResponse(error);
  }
}
