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

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

  const organizationId = auth.context.organization?.id;
  if (!organizationId) {
    return jsonFailure("请选择机构后维护家属反馈", 400);
  }

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

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

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "family.feedback.create",
    targetType: "family_feedback",
    targetId: feedback.id,
    result: "success",
    reason: `创建家属反馈：${feedback.elderName}`,
  });

  return jsonSuccess("家属反馈已创建", { feedback }, 201);
}
