import '../../../core/api/api_client.dart';
import '../../../core/api/api_exception.dart';
import '../../../core/api/api_paths.dart';
import '../../../core/platform/token_storage.dart';

class AuthRepository {
  final ApiClient _api;
  final ITokenStorage _storage;

  AuthRepository(this._api, this._storage);

  Future<String> login(String username, String password) async {
    try {
      final data = await _api.postJson(
        AuthApiPaths.login,
        body: {'username': username, 'password': password},
      );

      if (data is! Map<String, dynamic>) {
        throw const ApiException(
          type: ApiErrorType.unknown,
          message: 'Ogiltigt svar från servern.',
        );
      }

      final token = data['accessToken'];
      if (token is! String || token.isEmpty) {
        throw const ApiException(
          type: ApiErrorType.unknown,
          message: 'Svar saknar access token.',
        );
      }

      await _storage.saveToken(token);
      return token;
    } on ApiException {
      rethrow;
    } catch (_) {
      throw const ApiException(
        type: ApiErrorType.network,
        message: 'Kunde inte nå servern.',
      );
    }
  }

  Future<void> logout() => _storage.deleteToken();

  Future<String?> getToken() => _storage.getToken();
}
