import 'package:hive_ce/hive.dart';

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

part 'cached_data.g.dart';

/// Cached Data Model
///
/// Wrapper for caching API responses with timestamp and expiration.
/// Used for offline-first functionality and reducing API calls.
///
/// Example usage:
/// ```dart
/// final cachedProducts = CachedData(
///   data: products,
///   lastUpdated: DateTime.now(),
/// );
/// ```
@HiveType(typeId: HiveTypeIds.cachedData)
class CachedData extends HiveObject {
  CachedData({
    required this.data,
    required this.lastUpdated,
    this.expiresAt,
    this.source,
  });

  /// The cached data (stored as dynamic)
  @HiveField(0)
  final dynamic data;

  /// When the data was last updated
  @HiveField(1)
  final DateTime lastUpdated;

  /// Optional expiration time
  @HiveField(2)
  final DateTime? expiresAt;

  /// Source of the data (e.g., 'api', 'local')
  @HiveField(3)
  final String? source;

  /// Check if cache is expired
  bool get isExpired {
    if (expiresAt == null) return false;
    return DateTime.now().isAfter(expiresAt!);
  }

  /// Check if cache is fresh (not expired and within max age)
  bool isFresh(Duration maxAge) {
    if (isExpired) return false;
    final age = DateTime.now().difference(lastUpdated);
    return age <= maxAge;
  }

  /// Get age of cached data
  Duration get age => DateTime.now().difference(lastUpdated);

  /// Create a copy with updated data
  CachedData copyWith({
    dynamic data,
    DateTime? lastUpdated,
    DateTime? expiresAt,
    String? source,
  }) {
    return CachedData(
      data: data ?? this.data,
      lastUpdated: lastUpdated ?? this.lastUpdated,
      expiresAt: expiresAt ?? this.expiresAt,
      source: source ?? this.source,
    );
  }

  @override
  String toString() {
    return 'CachedData(lastUpdated: $lastUpdated, expiresAt: $expiresAt, source: $source, isExpired: $isExpired)';
  }
}
