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

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

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

  const organizationId = auth.context.organization?.id;
  if (!organizationId) {
    return jsonFailure("请选择机构后录入生命体征", 400);
  }

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

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

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "health.vital.create",
    targetType: "vital_record",
    targetId: created.vital.id,
    result: "success",
    reason: `录入生命体征：${created.vital.elderName}`,
  });

  return jsonSuccess("生命体征已录入", created, 201);
}
