import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/error/exceptions.dart';
import '../../domain/repositories/auth_repository.dart';
import 'auth_state.dart';

class AuthCubit extends Cubit<AuthState> {
  final AuthRepository _repo;

  AuthCubit(this._repo) : super(const AuthInitial());

  /// Auto-check on app launch — reads stored token, validates with API
  Future<void> checkAuth() async {
    emit(const AuthLoading());
    try {
      final user = await _repo.checkAuth();
      if (user != null) {
        emit(Authenticated(user));
      } else {
        emit(const Unauthenticated());
      }
    } catch (_) {
      emit(const Unauthenticated());
    }
  }

  /// Login with email + password
  Future<void> login(String email, String password) async {
    emit(const AuthLoading());
    try {
      final user = await _repo.login(email, password);
      emit(Authenticated(user));
    } on AuthException catch (e) {
      emit(AuthError(e.message));
    } on NetworkException catch (e) {
      emit(AuthError(e.message));
    } catch (e) {
      emit(AuthError(e.toString()));
    }
  }

  /// Register new account
  Future<void> register(String username, String email, String password) async {
    emit(const AuthLoading());
    try {
      final user = await _repo.register(username, email, password);
      emit(Authenticated(user));
    } on ConflictException catch (e) {
      emit(AuthError(e.message));
    } on NetworkException catch (e) {
      emit(AuthError(e.message));
    } catch (e) {
      emit(AuthError(e.toString()));
    }
  }

  /// Logout — clear token, reset state
  Future<void> logout() async {
    try {
      await _repo.logout();
    } catch (_) {}
    emit(const Unauthenticated());
  }

  /// Convenience getter for current user
  UserModel? get currentUser {
    final s = state;
    return s is Authenticated ? s.user : null;
  }
}