export type PrivacyRetentionPolicyFieldKey =
  | "store_raw_campaign_json"
  | "raw_campaign_json_retention_days"
  | "generated_eml_retention_days"
  | "stored_report_detail_retention_days"
  | "mock_mailbox_retention_days"
  | "audit_detail_retention_days"
  | "audit_detail_level";

export type RetentionPolicyLimitCarrier = {
  allow_lower_level_limits?: Partial<Record<PrivacyRetentionPolicyFieldKey, boolean>> | null;
};

export type PrivacyRetentionAuditDetailLevel = "full" | "redacted" | "minimal";

const auditDetailOrder: Record<PrivacyRetentionAuditDetailLevel, number> = { full: 0, redacted: 1, minimal: 2 };

export function privacyRetentionParentAllowsField(parentPolicy: RetentionPolicyLimitCarrier | null, key: PrivacyRetentionPolicyFieldKey): boolean {
  return !parentPolicy || parentPolicy.allow_lower_level_limits?.[key] !== false;
}

export function privacyRetentionLocalAllowsLowerLevel(
  policy: RetentionPolicyLimitCarrier,
  parentPolicy: RetentionPolicyLimitCarrier | null,
  key: PrivacyRetentionPolicyFieldKey,
  isSystem: boolean
): boolean {
  const localLimits = policy.allow_lower_level_limits ?? {};
  if (isSystem) return localLimits[key] !== false;
  const localValue = localLimits[key];
  if (localValue !== undefined) return localValue && privacyRetentionParentAllowsField(parentPolicy, key);
  return privacyRetentionParentAllowsField(parentPolicy, key);
}

export function privacyRetentionAuditDetailOptionDisabled(
  option: PrivacyRetentionAuditDetailLevel,
  parentValue?: PrivacyRetentionAuditDetailLevel | null
): boolean {
  const minimumOrder = parentValue ? auditDetailOrder[parentValue] : 0;
  return auditDetailOrder[option] < minimumOrder;
}
