import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../shared/utils/app_logger.dart';
import 'di_providers.dart';


class TraktScrobbleStatus {

  final DateTime? lastSuccessAt;


  final String? lastError;


  final int pendingCount;

  const TraktScrobbleStatus({
    this.lastSuccessAt,
    this.lastError,
    this.pendingCount = 0,
  });

  TraktScrobbleStatus copyWith({
    DateTime? lastSuccessAt,
    String? lastError,
    bool clearError = false,
    int? pendingCount,
  }) {
    return TraktScrobbleStatus(
      lastSuccessAt: lastSuccessAt ?? this.lastSuccessAt,
      lastError: clearError ? null : (lastError ?? this.lastError),
      pendingCount: pendingCount ?? this.pendingCount,
    );
  }
}


class TraktScrobbleStatusNotifier extends Notifier<TraktScrobbleStatus> {
  static const _tag = 'TraktStatus';

  @override
  TraktScrobbleStatus build() => const TraktScrobbleStatus();

  void recordSuccess() {
    state = state.copyWith(lastSuccessAt: DateTime.now(), clearError: true);
    _refreshPending();
  }

  void recordError(String error) {
    state = state.copyWith(lastError: error);
    _refreshPending();
  }


  Future<void> refreshPending() => _refreshPending();


  Future<void> retryPending() async {
    try {
      final queue = await ref.read(traktSyncQueueProvider.future);
      await queue.drain();
    } catch (e) {
      AppLogger.warn(_tag, 'retryPending failed', e);
    }
    await _refreshPending();
  }

  Future<void> _refreshPending() async {
    try {
      final queue = await ref.read(traktSyncQueueProvider.future);
      final count = await queue.pendingCount();
      state = state.copyWith(pendingCount: count);
    } catch (e) {
      AppLogger.debug(_tag, 'refreshPending failed', e);
    }
  }
}

final traktScrobbleStatusProvider =
    NotifierProvider<TraktScrobbleStatusNotifier, TraktScrobbleStatus>(
      TraktScrobbleStatusNotifier.new,
    );
