import { inject, Injectable, signal } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '@service/auth.service';

@Injectable({
  providedIn: 'root',
})
export class Oauth2Service {
  private router: Router = inject(Router);
  private authService: AuthService = inject(AuthService);
  private _error = signal<string>('');

  oauth(provider: string, code: string) {
    const oauth$ =
      provider === 'github' ? this.authService.githubAuth(code) : this.authService.googleAuth(code);

    oauth$.subscribe({
      next: () => {
        this.router.navigate(['/home']);
      },
      error: (err) => {
        this._error.set(
          err.error?.message || 'Authentifizierung fehlgeschlagen. Bitte versuchen Sie es erneut.'
        );

        setTimeout(() => {
          this.router.navigate(['/']);
        }, 3000);
      },
    });
  }

  public get error() {
    return this._error;
  }
}
