import { NextResponse } from 'next/server';
import {
  AnonymousStoreError,
  deleteAnonymousProfile,
  loginAnonymousProfile,
} from '@/lib/anonymous-store';

export const runtime = 'nodejs';

async function readCredentials(request: Request) {
  const body = await request.json().catch(() => ({}));
  return {
    codeName: String(body.codeName || ''),
    password: String(body.password || ''),
  };
}

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 { codeName, password } = await readCredentials(request);
    return NextResponse.json(await loginAnonymousProfile(codeName, password));
  } catch (error) {
    return errorResponse(error);
  }
}

export async function DELETE(request: Request) {
  try {
    const { codeName, password } = await readCredentials(request);
    return NextResponse.json(await deleteAnonymousProfile(codeName, password));
  } catch (error) {
    return errorResponse(error);
  }
}
