// 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 'dart:math';

import 'package:wyatt_authentication_bloc/wyatt_authentication_bloc.dart';
import 'package:wyatt_type_utils/wyatt_type_utils.dart';

/// {@template authentication_mock_data_source_impl}
/// Implementation of [AuthenticationRemoteDataSource] using Mocks.
/// {@endtemplate}
class AuthenticationMockDataSourceImpl<Data>
    extends AuthenticationRemoteDataSource<Data> {
  /// {@macro authentication_mock_data_source_impl}
  AuthenticationMockDataSourceImpl({
    this.mockData = const {
      'test@test.fr': Pair('test12', '1'),
      'alice@test.fr': Pair('alice12', '2'),
      'bob@test.fr': Pair('bob1234', '3'),
    },
    this.accessToken = 'mock_access_token',
  });

  /// Mock data.
  /// Format: <email, <password, id>>
  final Map<String, Pair<String, String>> mockData;

  /// Current user.
  Account? _currentUser;

  /// Access token.
  final String accessToken;

  /// A random delay to simulate network latency.
  Future<void> _randomDelay() async {
    await Future<void>.delayed(
      Duration(milliseconds: Random().nextInt(400) + 200),
    );
    return;
  }

  // SignUp/SignIn methods ====================================================

  /// {@macro signup_pwd}
  @override
  Future<Account> signUpWithEmailAndPassword({
    required String email,
    required String password,
  }) async {
    await _randomDelay();
    mockData[email] = Pair(password, '4');

    return _currentUser = Account(
      id: '4',
      isAnonymous: false,
      emailVerified: false,
      providerId: 'mock',
      email: email,
      accessToken: accessToken,
    );
  }

  /// {@macro signin_pwd}
  @override
  Future<Account> signInWithEmailAndPassword({
    required String email,
    required String password,
  }) async {
    await _randomDelay();
    final pair = mockData[email];

    if (pair == null || pair.left != password) {
      throw SignInWithEmailAndPasswordFailureMock();
    }

    return _currentUser = Account(
      id: pair.right!,
      isAnonymous: false,
      emailVerified: true,
      providerId: 'mock',
      email: email,
      accessToken: accessToken,
    );
  }

  /// {@macro signin_anom}
  @override
  Future<Account> signInAnonymously() async {
    await _randomDelay();
    return _currentUser = Account(
      id: '5',
      isAnonymous: true,
      emailVerified: false,
      providerId: 'mock',
      accessToken: accessToken,
    );
  }

  /// {@macro signin_google}
  @override
  Future<Account> signInWithGoogle() async {
    await _randomDelay();
    return _currentUser = Account(
      id: '6',
      isAnonymous: false,
      emailVerified: true,
      providerId: 'google.com',
      email: 'mock@gmail.com',
      accessToken: accessToken,
    );
  }

  /// {@macro signout}
  @override
  Future<void> signOut() async {
    await _randomDelay();
    _currentUser = null;
  }

  // Account management methods ===============================================

  /// {@macro refresh}
  @override
  Future<Account> refresh() async {
    await _randomDelay();
    if (_currentUser == null) {
      throw RefreshFailureMock();
    }
    return _currentUser!;
  }

  /// {@macro reauthenticate}
  @override
  Future<Account> reauthenticate() async {
    await _randomDelay();
    if (_currentUser == null) {
      throw ReauthenticateFailureMock();
    }
    return _currentUser!;
  }

  /// {@macro update_email}
  @override
  Future<Account> updateEmail({required String email}) async {
    throw UnimplementedError();
  }

  /// {@macro update_password}
  @override
  Future<Account> updatePassword({required String password}) async {
    throw UnimplementedError();
  }

  /// {@macro delete}
  @override
  Future<void> delete() async {
    throw UnimplementedError();
  }

  // Email related stuff ======================================================

  /// {@macro send_email_verification}
  @override
  Future<void> sendEmailVerification() async {
    throw UnimplementedError();
  }

  /// {@macro send_password_reset_email}
  @override
  Future<void> sendPasswordResetEmail({required String email}) async {
    throw UnimplementedError();
  }

  /// {@macro confirm_password_reset}
  @override
  Future<void> confirmPasswordReset({
    required String code,
    required String newPassword,
  }) async {
    throw UnimplementedError();
  }

  /// {@macro verify_password_reset_code}
  @override
  Future<bool> verifyPasswordResetCode({required String code}) async {
    throw UnimplementedError();
  }
}
