import 'package:flutter/material.dart';
import '../services/service_locator.dart';
import '../services/api/api_client.dart';

enum AuthStatus { initial, loading, authenticated, unauthenticated }

class AuthProvider extends ChangeNotifier {
  AuthStatus _status = AuthStatus.initial;
  String? _error;
  String? _username;

  AuthStatus get status => _status;
  String? get error => _error;
  String? get username => _username;
  bool get isAuthenticated => _status == AuthStatus.authenticated;

  Future<bool> login(String username, String secret) async {
    _status = AuthStatus.loading;
    _error = null;
    notifyListeners();

    try {
      final token = await ServiceLocator().auth.login(username, secret);
      ServiceLocator().setToken(token);
      _username = username;
      _status = AuthStatus.authenticated;
      notifyListeners();
      return true;
    } on ApiException catch (e) {
      _error = e.message;
      _status = AuthStatus.unauthenticated;
      notifyListeners();
      return false;
    } catch (e) {
      _error = 'خطا در اتصال به سرور';
      _status = AuthStatus.unauthenticated;
      notifyListeners();
      return false;
    }
  }

  void logout() {
    ServiceLocator().clearToken();
    _username = null;
    _status = AuthStatus.unauthenticated;
    _error = null;
    notifyListeners();
  }
}
