import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";
import { createChronicCondition, isMutationFailure } from "@/modules/health/server/operations";
import { validateChronicConditionInput } from "@/modules/health/types";

export async function POST(request: Request): Promise<Response> {
  const auth = await requirePermission("health:manage", {
    action: "health.condition.create",
    targetType: "chronic_condition",
  });

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

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

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

  const condition = await createChronicCondition({ ...input.data, organizationId });
  if (isMutationFailure(condition)) {
    return jsonFailure(condition.reason, condition.status);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "health.condition.create",
    targetType: "chronic_condition",
    targetId: condition.id,
    result: "success",
    reason: `新增慢病记录：${condition.elderName} / ${condition.name}`,
  });

  return jsonSuccess("慢病记录已创建", { condition }, 201);
}
