import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { createVersion, listVersions, type VersionSource, type VersionMilestone } from '@/lib/db/version-repo';
import { withAuth } from '@/core/auth';

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

const CreateVersionSchema = z.object({
  source: z.enum(['auto', 'manual', 'milestone']).default('manual'),
  label: z.string().optional(),
  milestone: z.enum(['generate', 'render', 'send', 'pre_restore']).optional(),
});

export const GET = withAuth<{ params: Promise<{ id: string }> }>(async (req: NextRequest, _ctx, ctx: { params: Promise<{ id: string }> }) => {
  const { id } = await ctx.params;
  return NextResponse.json({ versions: listVersions(id) });
});

export const POST = withAuth<{ params: Promise<{ id: string }> }>(async (req: NextRequest, _ctx, ctx: { params: Promise<{ id: string }> }) => {
  const { id } = await ctx.params;
  const body = await req.json().catch(() => ({}));
  const parsed = CreateVersionSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({
      error: 'Invalid version input',
      issues: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
    }, { status: 400 });
  }
  try {
    const version = createVersion({
      campaignId: id,
      source: parsed.data.source as VersionSource,
      label: parsed.data.label,
      milestone: parsed.data.milestone as VersionMilestone | undefined,
    });
    return NextResponse.json({ ok: true, version });
  } catch (e) {
    return NextResponse.json({ error: e instanceof Error ? e.message : 'create version failed' }, { status: 500 });
  }
});
