import { logError } from "@/lib/logger";
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";

export const runtime = "nodejs";

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = req.nextUrl;
    const type = searchParams.get("type") || "all";

    const [providersData, modelsData, pricingData, versionsData] = await Promise.all([
      query(
        `SELECT id, name, display_name, website, status, created_at, updated_at
         FROM ai_model_provider
         ORDER BY name`
      ),
      query(
        `SELECT m.id, m.name, m.modality, m.capability, m.context_length,
                m.max_output_tokens, m.training_cutoff, m.is_open_source, m.status,
                mv.model_id, mv.version,
                p.id as provider_id, p.name as provider_name
         FROM ai_model m
         JOIN ai_model_provider p ON p.id = m.provider_id
         LEFT JOIN ai_model_version mv ON mv.model_id = m.id AND mv.is_default = true
         ORDER BY p.name, m.name`
      ),
      query(
        `SELECT mp.id, mp.model_version_id, mp.input_price_per_1k_tokens, mp.output_price_per_1k_tokens,
                mp.currency, mp.effective_from,
                m.name as model_name, mv.model_id
         FROM ai_model_pricing mp
         JOIN ai_model_version mv ON mv.id = mp.model_version_id
         JOIN ai_model m ON m.id = mv.model_id
         ORDER BY mp.effective_from DESC
         LIMIT 200`
      ),
      query(
        `SELECT mv.id, mv.model_id, mv.version, mv.release_date, mv.change_log, mv.is_default, mv.status, mv.created_at
         FROM ai_model_version mv
         ORDER BY mv.model_id, mv.version`
      ),
    ]);

    const providersList = providersData.rows.map((r: Record<string, unknown>) => ({
      id: String(r.id),
      name: r.name,
      display_name: r.display_name,
      website: r.website,
      status: r.status,
      created_at: r.created_at,
      updated_at: r.updated_at,
      enabled: r.status === "active",
    }));

    const modelsList = modelsData.rows.map((r: Record<string, unknown>) => ({
      id: String(r.id),
      name: r.name,
      model_id: r.model_id ? `${r.model_id}/${r.version}` : r.id,
      modality: r.modality || "text",
      capability: r.capability || "chat",
      context_length: Number(r.context_length) || 8192,
      max_output_tokens: r.max_output_tokens ? Number(r.max_output_tokens) : null,
      training_cutoff: r.training_cutoff,
      is_open_source: r.is_open_source ?? false,
      enabled: r.status === "active",
      status: r.status,
      provider_id: String(r.provider_id),
      provider_name: r.provider_name,
    }));

    const pricingList = pricingData.rows.map((r: Record<string, unknown>) => ({
      id: Number(r.id),
      model_version_id: String(r.model_version_id),
      model_id: r.model_id,
      input_price_per_1k_tokens: String(r.input_price_per_1k_tokens),
      output_price_per_1k_tokens: String(r.output_price_per_1k_tokens),
      currency: r.currency,
      effective_from: r.effective_from,
      model_name: r.model_name,
    }));

    const versionsList = versionsData.rows.map((r: Record<string, unknown>) => ({
      id: String(r.id),
      model_id: String(r.model_id),
      version: r.version,
      release_date: r.release_date,
      change_log: r.change_log,
      is_default: r.is_default ?? false,
      status: r.status,
      created_at: r.created_at,
    }));

    return NextResponse.json({
      providers: providersList,
      models: modelsList,
      pricing: pricingList,
      versions: versionsList,
    });
  } catch (e) {
    logError("AI data error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
