import { NextRequest, NextResponse } from "next/server";
import { buildCommercialSnapshot } from "@/lib/commercial";
import { getMachineId } from "@/lib/license";
import { addAudit, readDb, writeDb } from "@/lib/store";
import type { LicenseConfig } from "@/lib/types";

export const dynamic = "force-dynamic";

export async function GET() {
  const db = await readDb();
  return NextResponse.json({
    ok: true,
    license: db.license,
    machineId: getMachineId(),
    snapshot: buildCommercialSnapshot(db),
  });
}

export async function POST(req: NextRequest) {
  const body = await req.json().catch(() => ({}));
  const db = await readDb();
  const patch: Partial<LicenseConfig> = {};

  if (body.clearRemote === true) {
    patch.remoteServerUrl = "";
    patch.remoteLicenseKey = "";
    patch.remoteStatus = undefined;
    patch.heartbeatStatus = "not_configured";
    patch.heartbeatError = "";
    patch.lastHeartbeatAt = undefined;
    patch.nextHeartbeatAt = undefined;
    patch.leaseExpiresAt = undefined;
  } else {
    if (typeof body.remoteServerUrl === "string") {
      patch.remoteServerUrl = body.remoteServerUrl.trim().replace(/\/+$/, "");
    }
    if (typeof body.remoteLicenseKey === "string" && body.remoteLicenseKey.trim()) {
      patch.remoteLicenseKey = body.remoteLicenseKey.trim();
    }
    if (typeof body.customerName === "string" && body.customerName.trim()) {
      patch.customerName = body.customerName.trim();
    }
  }

  db.license = {
    ...db.license,
    ...patch,
    machineId: db.license.machineId || getMachineId(),
  };
  addAudit(db, {
    type: "system",
    actor: "user",
    title: body.clearRemote === true ? "清除远程授权配置" : "更新远程授权配置",
    detail: db.license.remoteServerUrl || "未配置授权服务器",
    status: "completed",
  });
  await writeDb(db);
  return NextResponse.json({ ok: true, license: db.license, snapshot: buildCommercialSnapshot(db) });
}
