import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../domain/usecases/get_users_usecase.dart';
import '../../domain/usecases/sync_users_usecase.dart';
import 'users_state.dart';

/// State notifier for users
class UsersNotifier extends StateNotifier<UsersState> {
  final GetUsersUseCase getUsersUseCase;
  final SyncUsersUseCase syncUsersUseCase;

  UsersNotifier({
    required this.getUsersUseCase,
    required this.syncUsersUseCase,
  }) : super(const UsersState()) {
    // Load local users on initialization
    getUsers();
  }

  /// Get users from local storage (or API if not cached)
  Future<void> getUsers() async {
    state = state.copyWith(isLoading: true, error: null);

    final result = await getUsersUseCase();

    result.fold(
      (failure) => state = state.copyWith(
        isLoading: false,
        error: failure.message,
      ),
      (users) => state = state.copyWith(
        users: users,
        isLoading: false,
        error: null,
      ),
    );
  }

  /// Sync users from API (force refresh)
  Future<void> syncUsers() async {
    state = state.copyWith(isLoading: true, error: null);

    final result = await syncUsersUseCase();

    result.fold(
      (failure) => state = state.copyWith(
        isLoading: false,
        error: failure.message,
      ),
      (users) => state = state.copyWith(
        users: users,
        isLoading: false,
        error: null,
      ),
    );
  }
}
