import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { testConnection } from "@/lib/ollama";

export async function GET(req: NextRequest) {
  const session = await auth();
  if (!session?.user?.id) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const url = req.nextUrl.searchParams.get("url");
  let target = url;
  if (!target) {
    const user = await prisma.user.findUnique({ where: { id: session.user.id } });
    target = user?.ollamaUrl ?? "http://localhost:11434";
  }
  const result = await testConnection(target);
  return NextResponse.json(result);
}
