import { NextResponse } from "next/server";
import { mergeSettings } from "@/lib/store";
import { listModels, testConnection } from "@/lib/providers";
import { resolveGeneration } from "@/lib/model-caps";

export const dynamic = "force-dynamic";

// POST { action: "models" | "test" | "defaults", provider, settings }
// Settings come from the client form so you can test before saving.
export async function POST(request) {
  try {
    const { action, provider, settings } = await request.json();
    const merged = mergeSettings(settings);
    if (action === "models") {
      const models = await listModels(merged, provider);
      return NextResponse.json({ models });
    }
    if (action === "test") {
      const result = await testConnection(merged, provider);
      return NextResponse.json(result);
    }
    if (action === "defaults") {
      const probe = provider ? { ...merged, provider } : merged;
      const resolved = await resolveGeneration(probe);
      return NextResponse.json(resolved);
    }
    throw new Error("Unknown action.");
  } catch (e) {
    return NextResponse.json({ error: String(e.message || e) }, { status: 400 });
  }
}
