import { Router } from "express";
import { DEFAULT_MODEL, DEFAULT_OPENAI_BASE_URL } from "../config";
import { OpenAIResponsesClient } from "../services/openaiResponsesClient";
import { ok } from "../utils/http";

export function buildTestConnectionRouter(client: OpenAIResponsesClient): Router {
  const router = Router();

  router.post("/api/openai/test-connection", async (req, res, next) => {
    try {
      const body = (req.body ?? {}) as Record<string, unknown>;
      const result = await client.testConnection({
        apiKey: String(body.apiKey ?? process.env.OPENAI_API_KEY ?? ""),
        model: String(body.model ?? DEFAULT_MODEL),
        baseUrl: String(body.baseUrl ?? DEFAULT_OPENAI_BASE_URL)
      });
      ok(res, {
        ok: true,
        model: result.model,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      next(error);
    }
  });

  return router;
}
