import { NextRequest, NextResponse } from "next/server";
import { generateText } from "ai";
import { gateway } from "@ai-sdk/gateway";
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
import type { LanguageModel } from "ai";
import { requireApiAuth, handleApiError } from "@/lib/api-auth";
import { prisma } from "@/lib/db";

function getTestModel(provider: string, modelId: string, ollamaUrl: string): LanguageModel {
  if (provider === "ollama") {
    const baseURL = (ollamaUrl || process.env.OLLAMA_BASE_URL || "http://192.168.68.108:11434") + "/v1";
    const ollama = createOpenAICompatible({ name: "ollama", baseURL });
    return ollama.chatModel(modelId || "llava:7b");
  }

  return gateway(modelId || "openai/gpt-4o-mini");
}

export async function POST(request: NextRequest) {
  try {
    await requireApiAuth();
    const body = await request.json().catch(() => ({}));
    const provider = body.provider || "gateway";
    const modelId = body.model || "";

    const settings = await prisma.appSettings.findUnique({ where: { id: "singleton" } });
    const ollamaUrl = settings?.ollamaUrl || "";

    const model = getTestModel(provider, modelId, ollamaUrl);

    const { text } = await generateText({
      model,
      prompt: "Reply with exactly: OK",
      maxOutputTokens: 20,
    });

    return NextResponse.json({ ok: true, response: text.trim() });
  } catch (error) {
    return handleApiError(error);
  }
}
