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

type RouteContext = {
  params: Promise<{ id: string }>;
};

export async function PATCH(request: Request, context: RouteContext): Promise<Response> {
  const { id } = await context.params;
  const auth = await requirePermission("device:manage", { action: "device.asset.update", targetType: "device_asset", targetId: id });
  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 updateDeviceAsset({ ...input.data, id, organizationId });
  if (isDeviceMutationFailure(device)) {
    return jsonFailure(device.reason, device.status);
  }

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

  return jsonSuccess("设备已更新", { device });
}

export async function DELETE(_request: Request, context: RouteContext): Promise<Response> {
  const { id } = await context.params;
  const auth = await requirePermission("device:manage", { action: "device.asset.delete", targetType: "device_asset", targetId: id });
  if (!auth.success) {
    return auth.response;
  }

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

  const device = await deleteDeviceAsset({ id, organizationId });
  if (isDeviceMutationFailure(device)) {
    return jsonFailure(device.reason, device.status);
  }

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

  return jsonSuccess("设备已删除", { device });
}
