import { Injectable, NgZone } from '@angular/core';
import {
  FirebaseAuthentication,
  SignInResult,
  SignInWithPhoneNumberOptions
} from '@capacitor-firebase/authentication';
import { environment } from '@environments/environment';
import { Platform } from '@ionic/angular';
import { initializeApp } from 'firebase/app';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class FirebaseService {
  verificationId!: string;
  otpVerified$ = new Subject<SignInResult>();

  constructor(
    private readonly platform: Platform,
    private readonly ngZone: NgZone,
  ) {
    FirebaseAuthentication.removeAllListeners().then(() => {
      FirebaseAuthentication.addListener('phoneVerificationCompleted', (e) => {
        this.ngZone.run(() => {
          this.otpVerified$.next(e);
          this.signOut();
        });
      });
      FirebaseAuthentication.addListener('phoneVerificationFailed', (e) => {
        console.log('phoneVerificationFailed', e);
      });
      FirebaseAuthentication.addListener('phoneCodeSent', (e) => {
        this.verificationId = e.verificationId;
        console.log('phoneCodeSent', e);
      });
    });
  }

  async initialize(): Promise<void> {
    if (this.platform.is('capacitor')) {
      return;
    }
    /**
     * Only needed if the Firebase JavaScript SDK is used.
     *
     * Read more: https://github.com/robingenz/capacitor-firebase/blob/main/packages/authentication/docs/firebase-js-sdk.md
     */
    initializeApp(environment.firebaseOptions);
  }

  async signInWithPhoneNumber(
    options: SignInWithPhoneNumberOptions
  ): Promise<void> {
    return FirebaseAuthentication.signInWithPhoneNumber(options);
  }

  async confirmVerificationCode(
    verificationCode: string
  ): Promise<SignInResult> {
    return await FirebaseAuthentication.confirmVerificationCode({
      verificationId: this.verificationId,
      verificationCode,
    });
  }

  async signOut(): Promise<void> {
    await FirebaseAuthentication.signOut();
  }
}
