import { logError } from "@/lib/logger";
import { NextRequest, NextResponse } from "next/server";
import { createProvider, updateProvider, deleteProvider } from "@/lib/adminrpc/client";

export const runtime = "nodejs";

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

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

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