import { NextResponse } from 'next/server';
import { recordEvent } from '@/lib/auditDb';
import { generateTextAssets } from '@/lib/textGenerator';
import { loadSession, saveSession } from '@/lib/storage';
import type { GenerateTextRequest, GenerateTextResponse } from '@/lib/types';

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

export async function POST(req: Request) {
  const body = (await req.json()) as GenerateTextRequest;
  if (!body.sessionId) {
    return NextResponse.json({ error: 'sessionId required' }, { status: 400 });
  }

  const session = await loadSession(body.sessionId);
  if (!session) return NextResponse.json({ error: 'session not found' }, { status: 404 });
  if (!session.characterSpec) return NextResponse.json({ error: 'characterSpec required' }, { status: 409 });

  try {
    recordEvent({
      action: 'text.generate_started',
      sessionId: session.id,
      targetType: 'text',
      status: 'started',
      metadata: { templateIds: body.templateIds ?? null },
    });
    const generated = await generateTextAssets({ session, templateIds: body.templateIds });
    const nextIds = new Set(generated.textAssets.map(asset => asset.templateId));
    session.textAssets = [
      ...(session.textAssets ?? []).filter(asset => !nextIds.has(asset.templateId)),
      ...generated.textAssets,
    ];
    await saveSession(session);
    recordEvent({
      action: 'text.generate_completed',
      sessionId: session.id,
      targetType: 'text',
      status: 'ok',
      provider: generated.provider,
      metadata: { count: generated.textAssets.length },
    });

    const response: GenerateTextResponse = {
      textAssets: generated.textAssets,
      provider: generated.provider,
    };
    return NextResponse.json(response);
  } catch (error) {
    const message = String(error);
    recordEvent({
      action: 'text.generate_failed',
      sessionId: session.id,
      targetType: 'text',
      status: 'error',
      message,
    });
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
