// Copyright (C) 2023 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

import 'package:wyatt_authentication_bloc/src/domain/data_sources/local/authentication_cache_data_source.dart';
import 'package:wyatt_authentication_bloc/wyatt_authentication_bloc.dart';

/// {@template authentication_firebase_cache_data_source_impl}
/// A data source that manages the cache strategy.
/// This implementation uses Firebase.
/// {@endtemplate}
class AuthenticationFirebaseCacheDataSourceImpl<Data>
    extends AuthenticationCacheDataSource<Data> {
  /// {@macro authentication_firebase_cache_data_source_impl}
  AuthenticationFirebaseCacheDataSourceImpl({
    FirebaseAuth? firebaseAuth,
  }) : _firebaseAuth = firebaseAuth ?? FirebaseAuth.instance;

  final FirebaseAuth _firebaseAuth;

  // Already done by Firebase
  @override
  Future<void> cacheAccount(Account account) => Future.value();

  @override
  Future<Account?> getCachedAccount() async {
    final currentUser = _firebaseAuth.currentUser;
    if (currentUser == null) {
      return null;
    }

    final jwt = await currentUser.getIdToken(true);
    final currentAccount = AccountModel.fromFirebaseUser(
      currentUser,
      accessToken: jwt,
    );

    return currentAccount;
  }

  // Already done by Firebase
  @override
  Future<void> removeCachedAccount() => Future.value();
}
