import { logError } from "@/lib/logger";
import { NextRequest, NextResponse } from "next/server";
import { createModel, updateModel, deleteModel } from "@/lib/adminrpc/client";

export const runtime = "nodejs";

// POST /api/admin/ai/models — create model
export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const data = await createModel(body);
    return NextResponse.json(data);
  } catch (e) {
    const msg = e instanceof Error ? e.message : String(e);
    logError("Create model error:", e);
    return NextResponse.json({ error: `创建失败: ${msg}` }, { status: 500 });
  }
}

// PATCH /api/admin/ai/models?id={id} — update model
export async function PATCH(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const id = searchParams.get("id");
    if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
    const body = await req.json();
    const data = await updateModel(id, body);
    return NextResponse.json(data);
  } catch (e) {
    const msg = e instanceof Error ? e.message : String(e);
    logError("Update model error:", e);
    return NextResponse.json({ error: `更新失败: ${msg}` }, { status: 500 });
  }
}

// DELETE /api/admin/ai/models?id={id} — delete model
export async function DELETE(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const id = searchParams.get("id");
    if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
    const data = await deleteModel(id);
    return NextResponse.json(data);
  } catch (e) {
    const msg = e instanceof Error ? e.message : String(e);
    logError("Delete model error:", e);
    return NextResponse.json({ error: `删除失败: ${msg}` }, { status: 500 });
  }
}
