import { logError } from "@/lib/logger";
import { NextRequest, NextResponse } from "next/server";
import { createVersion, updateVersion, deleteVersion } from "@/lib/adminrpc/client";

export const runtime = "nodejs";

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

// PATCH /api/admin/ai/versions?id={id} — update version
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 updateVersion(id, body);
    return NextResponse.json(data);
  } catch (e) {
    const msg = e instanceof Error ? e.message : String(e);
    logError("Update version error:", e);
    return NextResponse.json({ error: `更新失败: ${msg}` }, { status: 500 });
  }
}

// DELETE /api/admin/ai/versions?id={id} — delete version
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 deleteVersion(id);
    return NextResponse.json(data);
  } catch (e) {
    const msg = e instanceof Error ? e.message : String(e);
    logError("Delete version error:", e);
    return NextResponse.json({ error: `删除失败: ${msg}` }, { status: 500 });
  }
}
