// 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:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:wyatt_authentication_bloc/src/core/constants/storage.dart';
import 'package:wyatt_authentication_bloc/wyatt_authentication_bloc.dart';

/// {@template authentication_secure_storage_cache_data_source_impl}
/// A data source that manages the cache strategy.
/// This implementation uses Secure Storage.
/// {@endtemplate}
class AuthenticationSecureStorageCacheDataSourceImpl<Data>
    extends AuthenticationCacheDataSource<Data> {
  /// {@macro authentication_secure_storage_cache_data_source_impl}
  const AuthenticationSecureStorageCacheDataSourceImpl({
    FlutterSecureStorage? secureStorage,
  }) : _secureStorage = secureStorage ?? const FlutterSecureStorage();

  final FlutterSecureStorage _secureStorage;

  @override
  Future<void> cacheAccount(Account account) async {
    await _secureStorage.write(
      key: AuthStorage.id,
      value: account.id,
    );
    await _secureStorage.write(
      key: AuthStorage.email,
      value: account.email,
    );
    await _secureStorage.write(
      key: AuthStorage.accessToken,
      value: account.accessToken,
    );
  }

  @override
  Future<Account?> getCachedAccount() async {
    final id = await _secureStorage.read(key: AuthStorage.id);
    final email = await _secureStorage.read(key: AuthStorage.email);
    final accessToken = await _secureStorage.read(key: AuthStorage.accessToken);

    if (id == null || email == null || accessToken == null) {
      return null;
    }

    final currentAccount = AccountModel.fromSecureStorage(
      id: id,
      email: email,
      accessToken: accessToken,
    );

    return currentAccount;
  }

  @override
  Future<void> removeCachedAccount() async {
    await _secureStorage.delete(key: AuthStorage.id);
    await _secureStorage.delete(key: AuthStorage.email);
    await _secureStorage.delete(key: AuthStorage.accessToken);
  }
}
