import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'auth_repository.dart';

final authStateProvider = StateNotifierProvider<AuthNotifier, AsyncValue<Map<String, dynamic>?>>((ref) {
  return AuthNotifier(ref.read(authRepositoryProvider));
});

class AuthNotifier extends StateNotifier<AsyncValue<Map<String, dynamic>?>> {
  final AuthRepository _repository;

  AuthNotifier(this._repository) : super(const AsyncValue.loading()) {
    checkLoginStatus();
  }

  Future<void> checkLoginStatus() async {
    try {
      final user = await _repository.getUser();
      if (user != null) {
        state = AsyncValue.data(user);
      } else {
        state = const AsyncValue.data(null);
      }
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    }
  }

  Future<void> login(String phone, String password) async {
    state = const AsyncValue.loading();
    try {
      final data = await _repository.login(phone, password);
      state = AsyncValue.data(data['user']);
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    }
  }

  Future<void> register(String phone, String password, String role) async {
    state = const AsyncValue.loading();
    try {
      await _repository.register(phone, password, role);
      // Auto login after register or just return success? 
      // For now, let's just ask them to login
      state = const AsyncValue.data(null); 
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    }
  }

  Future<void> logout() async {
    await _repository.logout();
    state = const AsyncValue.data(null);
  }
}
