/// Project Status Local Data Source
///
/// Handles local caching of project status list using Hive.
library;

import 'package:hive_ce/hive.dart';
import 'package:worker/core/constants/storage_constants.dart';
import 'package:worker/features/projects/data/models/project_status_model.dart';

/// Project Status Local Data Source
class ProjectStatusLocalDataSource {
  /// Get Hive box for project statuses
  Box<dynamic> get _box => Hive.box(HiveBoxNames.projectStatusBox);

  /// Save project status list to cache
  Future<void> cacheStatusList(List<ProjectStatusModel> statuses) async {
    // Clear existing cache
    await _box.clear();

    // Save each status with its index as key
    for (final status in statuses) {
      await _box.put(status.index, status);
    }
  }

  /// Get cached project status list
  List<ProjectStatusModel> getCachedStatusList() {
    try {
      final values = _box.values.whereType<ProjectStatusModel>().toList()
        // Sort by index
        ..sort((a, b) => a.index.compareTo(b.index));
      return values;
    } catch (e) {
      return [];
    }
  }

  /// Check if cache exists and is not empty
  bool hasCachedData() {
    return _box.isNotEmpty;
  }

  /// Clear all cached statuses
  Future<void> clearCache() async {
    await _box.clear();
  }
}
