import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";
import { createDeviceAsset, isDeviceMutationFailure, listDeviceOperationsData } from "@/modules/devices/server/operations";
import { validateDeviceAssetInput } from "@/modules/devices/types";

export async function GET(): Promise<Response> {
  const auth = await requirePermission("device:read", { action: "device.asset.list", targetType: "device_asset" });
  if (!auth.success) {
    return auth.response;
  }

  const organizationId = auth.context.organization?.id;
  if (!organizationId) {
    return jsonFailure("请选择机构后查看设备运维", 400);
  }

  const data = await listDeviceOperationsData(organizationId);
  return jsonSuccess("设备运维数据已加载", { data });
}

export async function POST(request: Request): Promise<Response> {
  const auth = await requirePermission("device:manage", { action: "device.asset.create", targetType: "device_asset" });
  if (!auth.success) {
    return auth.response;
  }

  const organizationId = auth.context.organization?.id;
  if (!organizationId) {
    return jsonFailure("请选择机构后维护设备", 400);
  }

  const input = validateDeviceAssetInput(await readJsonBody(request));
  if (!input.success) {
    return jsonFailure(input.reason);
  }

  const device = await createDeviceAsset({ ...input.data, organizationId });
  if (isDeviceMutationFailure(device)) {
    return jsonFailure(device.reason, device.status);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "device.asset.create",
    targetType: "device_asset",
    targetId: device.id,
    result: "success",
    reason: `创建设备：${device.name}`,
  });

  return jsonSuccess("设备已创建", { device }, 201);
}
