import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";
import { deleteMaintenanceTicket, isDeviceMutationFailure, updateMaintenanceTicket } from "@/modules/devices/server/operations";
import { validateMaintenanceTicketInput } 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.ticket.update", targetType: "maintenance_ticket", targetId: id });
  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 updateMaintenanceTicket({ ...input.data, id, organizationId });
  if (isDeviceMutationFailure(ticket)) {
    return jsonFailure(ticket.reason, ticket.status);
  }

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

  return jsonSuccess("维修工单已更新", { ticket });
}

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

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

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

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

  return jsonSuccess("维修工单已删除", { ticket });
}
