import 'package:sigap/src/features/auth/data/models/resources_model.dart';
import 'package:sigap/src/features/personalization/data/models/models/roles_model.dart';

class PermissionModel {
  final String id;
  final String action;
  final String resourceId;
  final String roleId;
  final DateTime createdAt;
  final DateTime updatedAt;
  final ResourceModel? resource;
  final RoleModel? role;

  PermissionModel({
    required this.id,
    required this.action,
    required this.resourceId,
    required this.roleId,
    required this.createdAt,
    required this.updatedAt,
    this.resource,
    this.role,
  });

  // Create a PermissionModel instance from a JSON object
  factory PermissionModel.fromJson(Map<String, dynamic> json) {
    return PermissionModel(
      id: json['id'] as String,
      action: json['action'] as String,
      resourceId: json['resource_id'] as String,
      roleId: json['role_id'] as String,
      createdAt: DateTime.parse(json['created_at'] as String),
      updatedAt: DateTime.parse(json['updated_at'] as String),
      resource:
          json['resource'] != null
              ? ResourceModel.fromJson(json['resource'] as Map<String, dynamic>)
              : null,
      role:
          json['role'] != null
              ? RoleModel.fromJson(json['role'] as Map<String, dynamic>)
              : null,
    );
  }

  // Convert a PermissionModel instance to a JSON object
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'action': action,
      'resource_id': resourceId,
      'role_id': roleId,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
    };
  }

  // Create a copy of the PermissionModel with updated fields
  PermissionModel copyWith({
    String? id,
    String? action,
    String? resourceId,
    String? roleId,
    DateTime? createdAt,
    DateTime? updatedAt,
    ResourceModel? resource,
    RoleModel? role,
  }) {
    return PermissionModel(
      id: id ?? this.id,
      action: action ?? this.action,
      resourceId: resourceId ?? this.resourceId,
      roleId: roleId ?? this.roleId,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
      resource: resource ?? this.resource,
      role: role ?? this.role,
    );
  }

  @override
  String toString() {
    return 'PermissionModel(id: $id, action: $action)';
  }
}
