/**
 * 规则条件操作符
 */
export type RuleOperator =
  | 'eq' // 等于
  | 'neq' // 不等于
  | 'gt' // 大于
  | 'gte' // 大于等于
  | 'lt' // 小于
  | 'lte' // 小于等于
  | 'within_days' // N天内
  | 'before_days' // N天前
  | 'in' // 在列表中
  | 'not_in'; // 不在列表中

/**
 * 可用于规则的字段
 */
export type RuleField =
  | 'registeredAt' // 注册时间
  | 'personalAdoptionCount' // 个人领养数
  | 'teamAdoptionCount' // 团队领养数
  | 'teamAddressCount' // 团队地址数
  | 'provinceAdoptionCount' // 省级授权领养数
  | 'cityAdoptionCount' // 市级授权领养数
  | 'kycStatus' // KYC状态
  | 'lastActiveAt' // 最后活跃时间
  | 'status'; // 用户状态

/**
 * 字段条件
 */
export interface FieldCondition {
  field: RuleField;
  operator: RuleOperator;
  value: number | string | string[];
}

/**
 * 组合条件
 */
export interface GroupCondition {
  type: 'AND' | 'OR';
  rules: (FieldCondition | GroupCondition)[];
}

/**
 * 规则条件 (顶层)
 */
export type RuleConditions = GroupCondition;

/**
 * 用户分类规则实体
 */
export class ClassificationRuleEntity {
  constructor(
    public readonly id: string,
    public readonly name: string,
    public readonly description: string | null,
    public readonly conditions: RuleConditions,
    public readonly isEnabled: boolean,
    public readonly createdAt: Date,
    public readonly updatedAt: Date,
  ) {}

  /**
   * 创建新规则
   */
  static create(params: {
    id: string;
    name: string;
    description?: string | null;
    conditions: RuleConditions;
  }): ClassificationRuleEntity {
    const now = new Date();
    return new ClassificationRuleEntity(
      params.id,
      params.name,
      params.description ?? null,
      params.conditions,
      true,
      now,
      now,
    );
  }

  /**
   * 更新规则
   */
  update(params: {
    name?: string;
    description?: string | null;
    conditions?: RuleConditions;
    isEnabled?: boolean;
  }): ClassificationRuleEntity {
    return new ClassificationRuleEntity(
      this.id,
      params.name ?? this.name,
      params.description !== undefined ? params.description : this.description,
      params.conditions ?? this.conditions,
      params.isEnabled ?? this.isEnabled,
      this.createdAt,
      new Date(),
    );
  }

  /**
   * 启用规则
   */
  enable(): ClassificationRuleEntity {
    return this.update({ isEnabled: true });
  }

  /**
   * 禁用规则
   */
  disable(): ClassificationRuleEntity {
    return this.update({ isEnabled: false });
  }

  /**
   * 验证规则条件格式是否有效
   */
  static validateConditions(conditions: unknown): conditions is RuleConditions {
    if (!conditions || typeof conditions !== 'object') {
      return false;
    }

    const group = conditions as GroupCondition;
    if (!['AND', 'OR'].includes(group.type)) {
      return false;
    }

    if (!Array.isArray(group.rules) || group.rules.length === 0) {
      return false;
    }

    return group.rules.every((rule) => {
      if ('type' in rule) {
        // 递归验证嵌套组
        return ClassificationRuleEntity.validateConditions(rule);
      } else {
        // 验证字段条件
        return ClassificationRuleEntity.validateFieldCondition(rule);
      }
    });
  }

  /**
   * 验证字段条件
   */
  private static validateFieldCondition(condition: unknown): condition is FieldCondition {
    if (!condition || typeof condition !== 'object') {
      return false;
    }

    const field = condition as FieldCondition;
    const validFields: RuleField[] = [
      'registeredAt',
      'personalAdoptionCount',
      'teamAdoptionCount',
      'teamAddressCount',
      'provinceAdoptionCount',
      'cityAdoptionCount',
      'kycStatus',
      'lastActiveAt',
      'status',
    ];

    const validOperators: RuleOperator[] = [
      'eq',
      'neq',
      'gt',
      'gte',
      'lt',
      'lte',
      'within_days',
      'before_days',
      'in',
      'not_in',
    ];

    if (!validFields.includes(field.field)) {
      return false;
    }

    if (!validOperators.includes(field.operator)) {
      return false;
    }

    if (field.value === undefined || field.value === null) {
      return false;
    }

    return true;
  }
}
