import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";
import { deleteFamilyContact, isFamilyMutationFailure, updateFamilyContact } from "@/modules/family/server/operations";
import { validateFamilyContactInput } 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.contact.update", targetType: "family_contact", targetId: id });
  if (!auth.success) {
    return auth.response;
  }

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

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

  const contact = await updateFamilyContact({ ...input.data, id, organizationId });
  if (isFamilyMutationFailure(contact)) {
    return jsonFailure(contact.reason, contact.status);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "family.contact.update",
    targetType: "family_contact",
    targetId: contact.id,
    result: "success",
    reason: `更新家属联系人：${contact.name}`,
  });

  return jsonSuccess("家属联系人已更新", { contact });
}

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

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

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

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "family.contact.delete",
    targetType: "family_contact",
    targetId: contact.id,
    result: "success",
    reason: `删除家属联系人：${contact.name}`,
  });

  return jsonSuccess("家属联系人已删除", { contact });
}
