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

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

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

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

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

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "device.ticket.create",
    targetType: "maintenance_ticket",
    targetId: ticket.id,
    result: "success",
    reason: `创建维修工单：${ticket.title}`,
  });

  return jsonSuccess("维修工单已创建", { ticket }, 201);
}
