import 'package:sigap/src/features/auth/data/models/permissions_model.dart';

class ResourceModel {
  final String id;
  final String name;
  final String? type;
  final String? description;
  final String? instanceRole;
  final String? relations;
  final Map<String, dynamic>? attributes;
  final DateTime createdAt;
  final DateTime updatedAt;
  final List<PermissionModel>? permissions;

  ResourceModel({
    required this.id,
    required this.name,
    this.type,
    this.description,
    this.instanceRole,
    this.relations,
    this.attributes,
    required this.createdAt,
    required this.updatedAt,
    this.permissions,
  });

  // Create a ResourceModel instance from a JSON object
  factory ResourceModel.fromJson(Map<String, dynamic> json) {
    return ResourceModel(
      id: json['id'] as String,
      name: json['name'] as String,
      type: json['type'] as String?,
      description: json['description'] as String?,
      instanceRole: json['instance_role'] as String?,
      relations: json['relations'] as String?,
      attributes: json['attributes'] as Map<String, dynamic>?,
      createdAt: DateTime.parse(json['created_at'] as String),
      updatedAt: DateTime.parse(json['updated_at'] as String),
      permissions:
          json['permissions'] != null
              ? (json['permissions'] as List)
                  .map(
                    (e) => PermissionModel.fromJson(e as Map<String, dynamic>),
                  )
                  .toList()
              : null,
    );
  }

  // Convert a ResourceModel instance to a JSON object
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'type': type,
      'description': description,
      'instance_role': instanceRole,
      'relations': relations,
      'attributes': attributes,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
    };
  }

  // Create a copy of the ResourceModel with updated fields
  ResourceModel copyWith({
    String? id,
    String? name,
    String? type,
    String? description,
    String? instanceRole,
    String? relations,
    Map<String, dynamic>? attributes,
    DateTime? createdAt,
    DateTime? updatedAt,
    List<PermissionModel>? permissions,
  }) {
    return ResourceModel(
      id: id ?? this.id,
      name: name ?? this.name,
      type: type ?? this.type,
      description: description ?? this.description,
      instanceRole: instanceRole ?? this.instanceRole,
      relations: relations ?? this.relations,
      attributes: attributes ?? this.attributes,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
      permissions: permissions ?? this.permissions,
    );
  }

  @override
  String toString() {
    return 'ResourceModel(id: $id, name: $name)';
  }
}
