import 'package:flutter/foundation.dart';

import '../../../../core/network/failure.dart';
import '../../domain/entities/dashboard_summary.dart';
import '../../domain/repositories/dashboard_repository.dart';

/// 대시보드 화면 상태를 관리하는 컨트롤러.
class DashboardController extends ChangeNotifier {
  DashboardController({required DashboardRepository repository})
    : _repository = repository;

  final DashboardRepository _repository;

  DashboardSummary? _summary;
  bool _isLoading = false;
  bool _isRefreshing = false;
  String? _errorMessage;

  DashboardSummary? get summary => _summary;
  bool get isLoading => _isLoading;
  bool get isRefreshing => _isRefreshing;
  String? get errorMessage => _errorMessage;

  /// 초기 로딩(캐시가 없을 때만 실행)
  Future<void> ensureLoaded() async {
    if (_summary != null || _isLoading) {
      return;
    }
    await refresh();
  }

  /// 서버에서 최신 요약을 다시 불러온다.
  Future<void> refresh() async {
    _isLoading = _summary == null;
    _isRefreshing = _summary != null;
    _errorMessage = null;
    notifyListeners();
    try {
      final result = await _repository.fetchSummary();
      _summary = result;
    } catch (error) {
      final failure = Failure.from(error);
      _errorMessage = failure.describe();
    } finally {
      _isLoading = false;
      _isRefreshing = false;
      notifyListeners();
    }
  }
}
