import { Injectable } from '@angular/core';
import { initializeApp, getApps, FirebaseApp } from 'firebase/app';
import {
  getAuth,
  Auth,
  GoogleAuthProvider,
  OAuthProvider,
  signInWithPopup,
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
  sendPasswordResetEmail,
  signOut,
  UserCredential
} from 'firebase/auth';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class FirebaseAuthService {
  private app: FirebaseApp;
  private auth: Auth;

  constructor() {
    // Avoid re-initializing if Firebase is already initialized
    this.app = getApps().length > 0
      ? getApps()[0]
      : initializeApp(environment.firebaseConfig);
    this.auth = getAuth(this.app);
  }

  async signInWithGoogle(): Promise<string> {
    const provider = new GoogleAuthProvider();
    const credential: UserCredential = await signInWithPopup(this.auth, provider);
    return credential.user.getIdToken();
  }

  async signInWithApple(): Promise<string> {
    const provider = new OAuthProvider('apple.com');
    provider.addScope('email');
    provider.addScope('name');
    const credential: UserCredential = await signInWithPopup(this.auth, provider);
    return credential.user.getIdToken();
  }

  async signInWithEmail(email: string, password: string): Promise<string> {
    const credential: UserCredential = await signInWithEmailAndPassword(this.auth, email, password);
    return credential.user.getIdToken();
  }

  async registerWithEmail(email: string, password: string): Promise<string> {
    const credential: UserCredential = await createUserWithEmailAndPassword(this.auth, email, password);
    return credential.user.getIdToken();
  }

  async sendPasswordReset(email: string): Promise<void> {
    return sendPasswordResetEmail(this.auth, email);
  }

  async signOut(): Promise<void> {
    return signOut(this.auth);
  }
}
