import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { importFromUrl } from "@/lib/ai/features/import-url";
import { validateWebhookUrl } from "@/lib/validate-webhook-url";
import { withUserKey } from "@/lib/ai/resolve-user-key";
import { requireFeatureEnabledResponse } from "@/lib/feature-flags";

const Schema = z.object({
  url: z.string().url(),
  provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]).optional(),
  model: z.string().optional(),
});

export async function POST(req: NextRequest) {
  const { session, response } = await requireSessionOrApiKey(req);
  if (response) return response;

  const featureDenied = await requireFeatureEnabledResponse(session!.user.id, "recipe_import_url");
  if (featureDenied) return featureDenied;

  const body = await req.json() as unknown;
  const parsed = Schema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
  }

  const ssrfError = await validateWebhookUrl(parsed.data.url);
  if (ssrfError) {
    return NextResponse.json({ error: ssrfError }, { status: 400 });
  }

  const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
  if (limited) return limited;

  const configResult = await resolveAiConfigOrError(() =>
    withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model })
  );
  if (!configResult.ok) return configResult.response;
  const aiConfig = configResult.data;

  const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro" | "family", () =>
    importFromUrl(parsed.data.url, aiConfig), { skipQuota: aiConfig.isByok }
  );
  if (!result.ok) return result.response;

  return NextResponse.json(result.data);
}
