// 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:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wyatt_authentication_bloc/src/domain/repositories/repositories.dart';
import 'package:wyatt_form_bloc/wyatt_form_bloc.dart';

part 'email_verification_state.dart';

/// {@template email_verification_cubit}
/// Cubit for sending email verification.
/// {@endtemplate}
class EmailVerificationCubit<Data> extends Cubit<EmailVerificationState> {
  /// {@macro email_verification_cubit}
  EmailVerificationCubit({
    required this.authenticationRepository,
  }) : super(const EmailVerificationState());

  /// The [AuthenticationRepository] used to send email verification.
  final AuthenticationRepository<Data> authenticationRepository;

  FutureOr<void> sendEmailVerification() async {
    emit(const EmailVerificationState(status: FormStatus.submissionInProgress));
    final response = await authenticationRepository.sendEmailVerification();
    emit(
      response.fold(
        (value) =>
            const EmailVerificationState(status: FormStatus.submissionSuccess),
        (error) => EmailVerificationState(
          errorMessage: error.message,
          status: FormStatus.submissionFailure,
        ),
      ),
    );
  }

  FutureOr<void> checkEmailVerification() async {
    emit(const EmailVerificationState(status: FormStatus.submissionInProgress));

    final refresh = await authenticationRepository.refresh();
    if (refresh.isErr) {
      final refreshError = refresh.err!;
      emit(
        EmailVerificationState(
          errorMessage: refreshError.message,
          status: FormStatus.submissionFailure,
        ),
      );
      return;
    }

    final session = await authenticationRepository.currentSession();
    final currentAccount = session.ok?.account;
    if (currentAccount != null) {
      emit(
        EmailVerificationState(
          isVerified: currentAccount.emailVerified,
          status: FormStatus.submissionSuccess,
        ),
      );
    } else {
      const EmailVerificationState(
        errorMessage: 'No current session',
        status: FormStatus.submissionFailure,
      );
    }
  }
}
