import 'package:equatable/equatable.dart';

int _parseInt(dynamic value, {int fallback = 0}) {
  if (value == null) return fallback;
  if (value is int) return value;
  if (value is double) return value.toInt();
  if (value is String) {
    final parsed = int.tryParse(value.trim());
    return parsed ?? fallback;
  }
  return fallback;
}

String _parseString(dynamic value, {String fallback = ''}) {
  if (value == null) return fallback;
  if (value is String) return value;
  return value.toString();
}

/// GET /app/linkage/rules 响应中的单条规则
class LinkageRuleBO extends Equatable {
  final int ruleId;
  final String ruleName;
  final String description;
  final String enabled; // "true"/"false" 或 "1"/"0"

  const LinkageRuleBO({
    required this.ruleId,
    required this.ruleName,
    required this.description,
    required this.enabled,
  });

  factory LinkageRuleBO.fromJson(Map<String, dynamic> json) {
    return LinkageRuleBO(
      ruleId: _parseInt(json['ruleId']),
      ruleName: _parseString(json['ruleName']),
      description: _parseString(json['description']),
      enabled: _parseString(json['enabled']),
    );
  }

  bool get isEnabled {
    return enabled == 'true' || enabled == '1';
  }

  @override
  List<Object?> get props => [ruleId, ruleName, description, enabled];
}

/// PUT /app/linkage/rules/toggle 响应
class LinkageRuleToggleBO extends Equatable {
  final int ruleId;
  final String enabled;

  const LinkageRuleToggleBO({required this.ruleId, required this.enabled});

  factory LinkageRuleToggleBO.fromJson(Map<String, dynamic> json) {
    return LinkageRuleToggleBO(
      ruleId: _parseInt(json['ruleId']),
      enabled: _parseString(json['enabled']),
    );
  }

  @override
  List<Object?> get props => [ruleId, enabled];
}
