import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { suggestUtm } from '@/modules/briefing/lib/suggest-utm';
import { withAuth } from '@/core/auth';

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

const RequestSchema = z.object({
  briefText: z.string().default(''),
  briefHtml: z.string().optional(),
  workspaceSlug: z.string().optional(),
  campaignName: z.string().optional(),
  existing: z
    .object({
      source: z.string().optional(),
      medium: z.string().optional(),
      campaign: z.string().optional(),
      content: z.string().optional(),
      term: z.string().optional(),
    })
    .default({}),
});

export const POST = withAuth(async (req: NextRequest, _ctx) => {
  try {
    const body = await req.json();
    const parsed = RequestSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json({ error: 'Invalid input', details: parsed.error.flatten() }, { status: 400 });
    }
    const result = await suggestUtm(parsed.data);
    return NextResponse.json({
      ok: true,
      suggestions: result.suggestions,
      meta: {
        modelUsed: result.modelUsed,
        tokensIn: result.tokensIn,
        tokensOut: result.tokensOut,
        durationMs: result.durationMs,
      },
    });
  } catch (err) {
    console.error('[/api/suggest-utm] error:', err);
    return NextResponse.json(
      { error: err instanceof Error ? err.message : 'Internal error' },
      { status: 500 },
    );
  }
});
