import { NextResponse } from 'next/server';
import { generateAssetPack } from '@/lib/packGenerator';
import { detectProvider } from '@/lib/providers';
import { loadSession, saveSession } from '@/lib/storage';
import { PACK_ORDER } from '@/lib/templates';
import type { GenerateAllPacksRequest, GenerateAllPacksResponse } from '@/lib/types';

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

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

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

  const sourceImage = session.images.find(image => image.id === imageId);
  if (!sourceImage) return NextResponse.json({ error: 'image not found' }, { status: 404 });
  if (sourceImage.status !== 'selected') {
    return NextResponse.json({ error: 'image must be selected before generating packs' }, { status: 400 });
  }

  try {
    const packs = [];
    const manifests = [];
    let workingSession = session;

    for (const kind of PACK_ORDER) {
      const generated = await generateAssetPack({ session: workingSession, sourceImage, kind });
      packs.push(generated.pack);
      manifests.push(generated.manifest);
      workingSession = {
        ...workingSession,
        characterSpec: generated.pack.characterSpec,
        packs: [
          ...(workingSession.packs ?? []).filter(existing => !(existing.kind === kind && existing.sourceImageId === imageId)),
          generated.pack,
        ],
        exports: [
          ...(workingSession.exports ?? []).filter(existing => !(existing.packKind === kind && existing.source.sourceImageId === imageId)),
          generated.manifest,
        ],
      };
    }

    await saveSession(workingSession);

    return NextResponse.json({
      packs,
      manifests,
      provider: detectProvider(),
    } satisfies GenerateAllPacksResponse);
  } catch (error) {
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}
