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

class TaskModel {
  final String id;
  final String title;
  final String? description;
  final String status;
  final String? priority;
  final String? serverId;
  final String? serverName;
  final String? assignedTo;
  final String? createdAt;
  final String? updatedAt;
  final String? completedAt;

  const TaskModel({
    required this.id,
    required this.title,
    this.description,
    required this.status,
    this.priority,
    this.serverId,
    this.serverName,
    this.assignedTo,
    this.createdAt,
    this.updatedAt,
    this.completedAt,
  });

  factory TaskModel.fromJson(Map<String, dynamic> json) {
    return TaskModel(
      id: json['id']?.toString() ?? '',
      title: json['title'] as String? ?? json['name'] as String? ?? 'Untitled',
      description: json['description'] as String?,
      status: json['status'] as String? ?? 'unknown',
      priority: json['priority'] as String?,
      serverId: json['serverId'] as String? ?? json['server_id'] as String?,
      serverName: json['serverName'] as String? ?? json['server_name'] as String?,
      assignedTo: json['assignedTo'] as String? ?? json['assigned_to'] as String?,
      createdAt: json['createdAt'] as String? ?? json['created_at'] as String?,
      updatedAt: json['updatedAt'] as String? ?? json['updated_at'] as String?,
      completedAt: json['completedAt'] as String? ?? json['completed_at'] as String?,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      if (description != null) 'description': description,
      'status': status,
      if (priority != null) 'priority': priority,
      if (serverId != null) 'serverId': serverId,
      if (assignedTo != null) 'assignedTo': assignedTo,
    };
  }

  /// Converts this model to a domain [Task] entity.
  Task toEntity() {
    return Task(
      id: id,
      title: title,
      description: description,
      status: status,
      priority: priority,
      serverId: serverId,
      serverName: serverName,
      assignedTo: assignedTo,
      createdAt: _parseDateTime(createdAt),
      updatedAt: _parseDateTime(updatedAt),
      completedAt: _parseDateTime(completedAt),
    );
  }

  /// Creates a model from a domain [Task] entity.
  factory TaskModel.fromEntity(Task entity) {
    return TaskModel(
      id: entity.id,
      title: entity.title,
      description: entity.description,
      status: entity.status,
      priority: entity.priority,
      serverId: entity.serverId,
      serverName: entity.serverName,
      assignedTo: entity.assignedTo,
      createdAt: entity.createdAt?.toIso8601String(),
      updatedAt: entity.updatedAt?.toIso8601String(),
      completedAt: entity.completedAt?.toIso8601String(),
    );
  }

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