import 'dart:convert';
import 'package:hive_ce/hive.dart';
import 'package:worker/core/constants/storage_constants.dart';
import 'package:worker/core/database/models/enums.dart';

part 'chat_room_model.g.dart';

@HiveType(typeId: HiveTypeIds.chatRoomModel)
class ChatRoomModel extends HiveObject {
  ChatRoomModel({
    required this.chatRoomId,
    required this.roomType,
    this.relatedQuoteId,
    this.relatedOrderId,
    required this.participants,
    this.roomName,
    required this.isActive,
    this.lastActivity,
    required this.createdAt,
    this.createdBy,
  });

  @HiveField(0)
  final String chatRoomId;
  @HiveField(1)
  final RoomType roomType;
  @HiveField(2)
  final String? relatedQuoteId;
  @HiveField(3)
  final String? relatedOrderId;
  @HiveField(4)
  final String participants;
  @HiveField(5)
  final String? roomName;
  @HiveField(6)
  final bool isActive;
  @HiveField(7)
  final DateTime? lastActivity;
  @HiveField(8)
  final DateTime createdAt;
  @HiveField(9)
  final String? createdBy;

  factory ChatRoomModel.fromJson(Map<String, dynamic> json) => ChatRoomModel(
    chatRoomId: json['chat_room_id'] as String,
    roomType: RoomType.values.firstWhere((e) => e.name == json['room_type']),
    relatedQuoteId: json['related_quote_id'] as String?,
    relatedOrderId: json['related_order_id'] as String?,
    participants: jsonEncode(json['participants']),
    roomName: json['room_name'] as String?,
    isActive: json['is_active'] as bool? ?? true,
    lastActivity: json['last_activity'] != null
        ? DateTime.parse(json['last_activity']?.toString() ?? '')
        : null,
    createdAt: DateTime.parse(json['created_at']?.toString() ?? ''),
    createdBy: json['created_by'] as String?,
  );

  Map<String, dynamic> toJson() => {
    'chat_room_id': chatRoomId,
    'room_type': roomType.name,
    'related_quote_id': relatedQuoteId,
    'related_order_id': relatedOrderId,
    'participants': jsonDecode(participants),
    'room_name': roomName,
    'is_active': isActive,
    'last_activity': lastActivity?.toIso8601String(),
    'created_at': createdAt.toIso8601String(),
    'created_by': createdBy,
  };

  List<String>? get participantsList {
    try {
      final decoded = jsonDecode(participants) as List;
      return decoded.map((e) => e.toString()).toList();
    } catch (e) {
      return null;
    }
  }
}
