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

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

export async function PATCH(request: Request, context: RouteContext): Promise<Response> {
  const { id } = await context.params;
  const auth = await requirePermission("family:manage", { action: "family.visit.update", targetType: "family_visit", targetId: id });
  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 updateFamilyVisit({ ...input.data, id, 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.update",
    targetType: "family_visit",
    targetId: visit.id,
    result: "success",
    reason: `更新探访预约：${visit.elderName}`,
  });

  return jsonSuccess("探访预约已更新", { visit });
}

export async function DELETE(_request: Request, context: RouteContext): Promise<Response> {
  const { id } = await context.params;
  const auth = await requirePermission("family:manage", { action: "family.visit.delete", targetType: "family_visit", targetId: id });
  if (!auth.success) {
    return auth.response;
  }

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

  const visit = await deleteFamilyVisit({ id, organizationId });
  if (isFamilyMutationFailure(visit)) {
    return jsonFailure(visit.reason, visit.status);
  }

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

  return jsonSuccess("探访预约已删除", { visit });
}
