import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";
import { createFamilyVisit, isFamilyMutationFailure } from "@/modules/family/server/operations";
import { validateFamilyVisitInput } from "@/modules/family/types";

export async function POST(request: Request): Promise<Response> {
  const auth = await requirePermission("family:manage", { action: "family.visit.create", targetType: "family_visit" });
  if (!auth.success) {
    return auth.response;
  }

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

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

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

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "family.visit.create",
    targetType: "family_visit",
    targetId: visit.id,
    result: "success",
    reason: `创建探访预约：${visit.elderName}`,
  });

  return jsonSuccess("探访预约已创建", { visit }, 201);
}
