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

part 'showroom_model.g.dart';

@HiveType(typeId: HiveTypeIds.showroomModel)
class ShowroomModel extends HiveObject {
  ShowroomModel({
    required this.showroomId,
    required this.title,
    required this.description,
    this.coverImage,
    this.link360,
    required this.area,
    required this.style,
    required this.location,
    this.galleryImages,
    required this.viewCount,
    required this.isFeatured,
    required this.isActive,
    this.publishedAt,
    this.createdBy,
  });

  @HiveField(0)
  final String showroomId;
  @HiveField(1)
  final String title;
  @HiveField(2)
  final String description;
  @HiveField(3)
  final String? coverImage;
  @HiveField(4)
  final String? link360;
  @HiveField(5)
  final double area;
  @HiveField(6)
  final String style;
  @HiveField(7)
  final String location;
  @HiveField(8)
  final String? galleryImages;
  @HiveField(9)
  final int viewCount;
  @HiveField(10)
  final bool isFeatured;
  @HiveField(11)
  final bool isActive;
  @HiveField(12)
  final DateTime? publishedAt;
  @HiveField(13)
  final String? createdBy;

  factory ShowroomModel.fromJson(Map<String, dynamic> json) => ShowroomModel(
    showroomId: json['showroom_id'] as String,
    title: json['title'] as String,
    description: json['description'] as String,
    coverImage: json['cover_image'] as String?,
    link360: json['link_360'] as String?,
    area: (json['area'] as num).toDouble(),
    style: json['style'] as String,
    location: json['location'] as String,
    galleryImages: json['gallery_images'] != null
        ? jsonEncode(json['gallery_images'])
        : null,
    viewCount: json['view_count'] as int? ?? 0,
    isFeatured: json['is_featured'] as bool? ?? false,
    isActive: json['is_active'] as bool? ?? true,
    publishedAt: json['published_at'] != null
        ? DateTime.parse(json['published_at']?.toString() ?? '')
        : null,
    createdBy: json['created_by'] as String?,
  );

  Map<String, dynamic> toJson() => {
    'showroom_id': showroomId,
    'title': title,
    'description': description,
    'cover_image': coverImage,
    'link_360': link360,
    'area': area,
    'style': style,
    'location': location,
    'gallery_images': galleryImages != null ? jsonDecode(galleryImages!) : null,
    'view_count': viewCount,
    'is_featured': isFeatured,
    'is_active': isActive,
    'published_at': publishedAt?.toIso8601String(),
    'created_by': createdBy,
  };

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