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

import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:rxdart/subjects.dart';
import 'package:wyatt_authentication_bloc/src/core/exceptions/exceptions.dart';
import 'package:wyatt_authentication_bloc/src/data/models/models.dart';
import 'package:wyatt_authentication_bloc/src/domain/data_sources/remote/authentication_remote_data_source.dart';
import 'package:wyatt_authentication_bloc/src/domain/entities/account.dart';
import 'package:wyatt_type_utils/wyatt_type_utils.dart';

/// {@template authentication_firebase_data_source_impl}
/// Implementation of [AuthenticationRemoteDataSource] using Firebase.
/// {@endtemplate}
class AuthenticationFirebaseDataSourceImpl<Data>
    extends AuthenticationRemoteDataSource<Data> {
  /// {@macro authentication_firebase_data_source_impl}
  AuthenticationFirebaseDataSourceImpl({
    FirebaseAuth? firebaseAuth,
    GoogleSignIn? googleSignIn,
  })  : _firebaseAuth = firebaseAuth ?? FirebaseAuth.instance,
        _googleSignIn = googleSignIn ?? GoogleSignIn() {
    _latestCredentials = BehaviorSubject();
  }

  late StreamController<UserCredential?> _latestCredentials;

  final FirebaseAuth _firebaseAuth;
  final GoogleSignIn _googleSignIn;

  Future<Account> _addToCredentialStream(
    UserCredential userCredential,
  ) async {
    final currentUser = _firebaseAuth.currentUser;
    final jwt = await currentUser?.getIdToken(true);
    final account = AccountModel.fromFirebaseUserCredential(
      userCredential,
      accessToken: jwt,
    );

    _latestCredentials.add(userCredential);

    return account;
  }

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

  /// {@macro signup_pwd}
  @override
  Future<Account> signUpWithEmailAndPassword({
    required String email,
    required String password,
  }) async {
    try {
      final userCredential = await _firebaseAuth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );

      return _addToCredentialStream(userCredential);
    } on FirebaseAuthException catch (e) {
      throw SignUpWithEmailAndPasswordFailureFirebase.fromCode(e.code);
    } catch (_) {
      throw SignUpWithEmailAndPasswordFailureFirebase();
    }
  }

  /// {@macro signin_pwd}
  @override
  Future<Account> signInWithEmailAndPassword({
    required String email,
    required String password,
  }) async {
    try {
      final userCredential = await _firebaseAuth.signInWithEmailAndPassword(
        email: email,
        password: password,
      );

      return _addToCredentialStream(userCredential);
    } on FirebaseAuthException catch (e) {
      throw SignInWithEmailAndPasswordFailureFirebase.fromCode(e.code);
    } catch (_) {
      throw SignInWithEmailAndPasswordFailureFirebase();
    }
  }

  /// {@macro signin_anom}
  @override
  Future<Account> signInAnonymously() async {
    try {
      final userCredential = await _firebaseAuth.signInAnonymously();

      return _addToCredentialStream(userCredential);
    } on FirebaseAuthException catch (e) {
      throw SignInAnonymouslyFailureFirebase.fromCode(e.code);
    } catch (_) {
      throw SignInAnonymouslyFailureFirebase();
    }
  }

  /// {@macro signin_google}
  @override
  Future<Account> signInWithGoogle() async {
    try {
      // Trigger the authentication flow
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();

      // Obtain the auth details from the request
      final GoogleSignInAuthentication? googleAuth =
          await googleUser?.authentication;

      // Create a new credential
      final credential = GoogleAuthProvider.credential(
        accessToken: googleAuth?.accessToken,
        idToken: googleAuth?.idToken,
      );

      final userCredential =
          await _firebaseAuth.signInWithCredential(credential);

      return _addToCredentialStream(userCredential);
    } on FirebaseAuthException catch (e) {
      throw SignInWithGoogleFailureFirebase.fromCode(e.code);
    } catch (_) {
      throw SignInWithGoogleFailureFirebase();
    }
  }

  /// {@macro signout}
  @override
  Future<void> signOut() async {
    try {
      _latestCredentials.add(null);
      await _firebaseAuth.signOut();
    } catch (_) {
      throw SignOutFailureFirebase();
    }
  }

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

  /// {@macro refresh}
  @override
  Future<Account> refresh() async {
    try {
      final jwt = await _firebaseAuth.currentUser?.getIdToken(true);
      final account = AccountModel.fromFirebaseUser(
        _firebaseAuth.currentUser,
        accessToken: jwt,
      );

      return account;
    } on FirebaseAuthException catch (e) {
      throw RefreshFailureFirebase.fromCode(e.code);
    } catch (_) {
      throw RefreshFailureFirebase();
    }
  }

  /// {@macro reauthenticate}
  @override
  Future<Account> reauthenticate() async {
    final latestCreds =
        await _latestCredentials.stream.asBroadcastStream().last;
    try {
      if (latestCreds?.credential != null) {
        await _firebaseAuth.currentUser
            ?.reauthenticateWithCredential(latestCreds!.credential!);
      } else {
        throw Exception(); // Get caught just after.
      }

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

      return account;
    } on FirebaseAuthException catch (e) {
      throw ReauthenticateFailureFirebase.fromCode(e.code);
    } catch (_) {
      throw ReauthenticateFailureFirebase();
    }
  }

  /// {@macro update_email}
  @override
  Future<Account> updateEmail({required String email}) async {
    try {
      await _firebaseAuth.currentUser!.updateEmail(email);
      final jwt = await _firebaseAuth.currentUser!.getIdToken(true);
      final account = AccountModel.fromFirebaseUser(
        _firebaseAuth.currentUser,
        accessToken: jwt,
      );

      return account;
    } on FirebaseAuthException catch (e) {
      throw UpdateEmailFailureFirebase.fromCode(e.code);
    } catch (_) {
      throw UpdateEmailFailureFirebase();
    }
  }

  /// {@macro update_password}
  @override
  Future<Account> updatePassword({required String password}) async {
    try {
      await _firebaseAuth.currentUser!.updatePassword(password);
      final jwt = await _firebaseAuth.currentUser!.getIdToken(true);
      final account = AccountModel.fromFirebaseUser(
        _firebaseAuth.currentUser,
        accessToken: jwt,
      );

      return account;
    } on FirebaseAuthException catch (e) {
      throw UpdatePasswordFailureFirebase.fromCode(e.code);
    } catch (_) {
      throw UpdatePasswordFailureFirebase();
    }
  }

  /// {@macro delete}
  @override
  Future<void> delete() async {
    try {
      await _firebaseAuth.currentUser!.delete();
    } on FirebaseAuthException catch (e) {
      throw DeleteAccountFailureFirebase.fromCode(e.code);
    } catch (_) {
      throw DeleteAccountFailureFirebase();
    }
  }

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

  /// {@macro send_email_verification}
  @override
  Future<void> sendEmailVerification() async {
    try {
      await _firebaseAuth.currentUser!.sendEmailVerification();
    } on FirebaseAuthException catch (e) {
      throw SendEmailVerificationFailureFirebase.fromCode(e.code);
    } catch (_) {
      throw SendEmailVerificationFailureFirebase();
    }
  }

  /// {@macro send_password_reset_email}
  @override
  Future<void> sendPasswordResetEmail({required String email}) async {
    try {
      await _firebaseAuth.sendPasswordResetEmail(email: email);
    } on FirebaseAuthException catch (e) {
      throw SendPasswordResetEmailFailureFirebase.fromCode(e.code);
    } catch (_) {
      throw SendPasswordResetEmailFailureFirebase();
    }
  }

  /// {@macro confirm_password_reset}
  @override
  Future<void> confirmPasswordReset({
    required String code,
    required String newPassword,
  }) async {
    try {
      await _firebaseAuth.confirmPasswordReset(
        code: code,
        newPassword: newPassword,
      );
    } on FirebaseAuthException catch (e) {
      throw ConfirmPasswordResetFailureFirebase.fromCode(e.code);
    } catch (_) {
      throw ConfirmPasswordResetFailureFirebase();
    }
  }

  /// {@macro verify_password_reset_code}
  @override
  Future<bool> verifyPasswordResetCode({required String code}) async {
    try {
      final email = await _firebaseAuth.verifyPasswordResetCode(code);
      return email.isNotNullOrEmpty;
    } on FirebaseAuthException catch (e) {
      throw VerifyPasswordResetCodeFailureFirebase.fromCode(e.code);
    } catch (_) {
      throw VerifyPasswordResetCodeFailureFirebase();
    }
  }
}
