import '../../domain/entities/standing_order.dart';

class StandingOrderModel {
  final String id;
  final String name;
  final String triggerType;
  final String? schedule;
  final String? agentInstructions;
  final String? decisionBoundary;
  final bool isActive;
  final String? lastExecutedAt;
  final String? createdAt;

  const StandingOrderModel({
    required this.id,
    required this.name,
    required this.triggerType,
    this.schedule,
    this.agentInstructions,
    this.decisionBoundary,
    required this.isActive,
    this.lastExecutedAt,
    this.createdAt,
  });

  factory StandingOrderModel.fromJson(Map<String, dynamic> json) {
    return StandingOrderModel(
      id: json['id']?.toString() ?? '',
      name: json['name'] as String? ?? 'Untitled',
      triggerType: json['triggerType'] as String? ??
          json['trigger_type'] as String? ??
          'cron',
      schedule: json['schedule'] as String?,
      agentInstructions: json['agentInstructions'] as String? ??
          json['agent_instructions'] as String?,
      decisionBoundary: json['decisionBoundary'] as String? ??
          json['decision_boundary'] as String?,
      isActive: json['isActive'] as bool? ??
          json['is_active'] as bool? ??
          false,
      lastExecutedAt: json['lastExecutedAt'] as String? ??
          json['last_executed_at'] as String?,
      createdAt: json['createdAt'] as String? ??
          json['created_at'] as String?,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'triggerType': triggerType,
      if (schedule != null) 'schedule': schedule,
      if (agentInstructions != null) 'agentInstructions': agentInstructions,
      if (decisionBoundary != null) 'decisionBoundary': decisionBoundary,
      'isActive': isActive,
    };
  }

  /// Converts this model to a domain [StandingOrder] entity.
  StandingOrder toEntity() {
    return StandingOrder(
      id: id,
      name: name,
      triggerType: triggerType,
      schedule: schedule,
      agentInstructions: agentInstructions,
      decisionBoundary: decisionBoundary,
      isActive: isActive,
      lastExecutedAt: _parseDateTime(lastExecutedAt),
      createdAt: _parseDateTime(createdAt),
    );
  }

  /// Creates a model from a domain [StandingOrder] entity.
  factory StandingOrderModel.fromEntity(StandingOrder entity) {
    return StandingOrderModel(
      id: entity.id,
      name: entity.name,
      triggerType: entity.triggerType,
      schedule: entity.schedule,
      agentInstructions: entity.agentInstructions,
      decisionBoundary: entity.decisionBoundary,
      isActive: entity.isActive,
      lastExecutedAt: entity.lastExecutedAt?.toIso8601String(),
      createdAt: entity.createdAt?.toIso8601String(),
    );
  }

  static DateTime? _parseDateTime(String? value) {
    if (value == null) return null;
    return DateTime.tryParse(value);
  }
}
