import { ChangeDetectionStrategy, Component, inject, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../../service/auth.service';
import { OAuthService } from 'angular-oauth2-oidc';

@Component({
  selector: 'app-login-success',
  standalone: true,
  imports: [],
  templateUrl: './login-success.component.html',
  styleUrl: './login-success.component.css',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export default class LoginSuccessComponent implements OnInit {
  private authService: AuthService = inject(AuthService);
  private oauthService: OAuthService = inject(OAuthService);
  private router: Router = inject(Router);

  async ngOnInit() {
    try {
      if (this.oauthService.hasValidAccessToken()) {
        this.router.navigate(['/home']);
      } else {
        setTimeout(() => {
          if (this.oauthService.hasValidAccessToken() || this.authService.getUser()) {
            this.router.navigate(['/home']);
          } else {
            this.router.navigate(['/']);
          }
        }, 3000);
      }
    } catch (err) {
      console.error('Error during login callback:', err);
      setTimeout(() => {
        if (this.authService.isLoggedIn()) {
          this.router.navigate(['/home']);
        } else {
          this.router.navigate(['/']);
        }
      }, 3000);
    }
  }
}
