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, upsertHealthProfile } from "@/modules/health/server/operations";
import { validateHealthProfileInput } from "@/modules/health/types";

type RouteContext = {
  params: Promise<{
    elderId: string;
  }>;
};

export async function PUT(request: Request, context: RouteContext): Promise<Response> {
  const { elderId } = await context.params;
  const auth = await requirePermission("health:manage", {
    action: "health.profile.upsert",
    targetType: "elder",
    targetId: elderId,
  });

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

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

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

  const profile = await upsertHealthProfile({ ...input.data, elderId, organizationId });
  if (isMutationFailure(profile)) {
    return jsonFailure(profile.reason, profile.status);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "health.profile.upsert",
    targetType: "elder",
    targetId: elderId,
    result: "success",
    reason: `维护健康档案：${profile.elderName}`,
  });

  return jsonSuccess("健康档案已保存", { profile });
}
