import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";
import { isMutationFailure, updateHealthReview } from "@/modules/health/server/operations";
import { validateHealthReviewUpdateInput } from "@/modules/health/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("health:manage", {
    action: "health.review.update",
    targetType: "health_review",
    targetId: id,
  });

  if (!auth.success) {
    return auth.response;
  }

  const organizationId = auth.context.organization?.id;
  if (!organizationId) {
    return jsonFailure("请选择机构后处理异常复核", 400);
  }

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

  const review = await updateHealthReview({
    ...input.data,
    id,
    organizationId,
    accountId: auth.context.account.id,
  });
  if (isMutationFailure(review)) {
    return jsonFailure(review.reason, review.status);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "health.review.update",
    targetType: "health_review",
    targetId: review.id,
    result: "success",
    reason: `处理健康异常复核：${review.elderName}`,
  });

  return jsonSuccess("异常复核已更新", { review });
}
