import {Component, OnInit} from '@angular/core';
import {AuthService} from '../../_services/auth.service';
import {Users} from '../../_models/users';
import {catchError, of} from 'rxjs';
import {NgIf} from '@angular/common';
import {Router, RouterLink} from '@angular/router';

@Component({
  selector: 'app-sidbar',
  imports: [
    NgIf,
    RouterLink
  ],
  templateUrl: './sidbar.component.html',
  styleUrl: './sidbar.component.css'
})
export class SidbarComponent implements OnInit {

  user: Users = { id: 0, email: '', firstname: '', lastname: '', password_hash: '', updated_at: new Date(), created_at: new Date() };

  constructor(private authService: AuthService, private router: Router) {}

  ngOnInit(): void {
    this.checkAuthAndLoadUser();

  }

  checkAuthAndLoadUser(): void {
    this.authService.isAuthenticated().subscribe(isAuthenticated => {
      if (isAuthenticated) {
        this.loadUsers();
      } else {
        this.user = { id: 0, email: '', firstname: '', lastname: '', password_hash: '', updated_at: new Date(), created_at: new Date() };
      }
    });
  }

  loadUsers(): void {
    this.authService.getProfil().pipe(
      catchError(error => {
        console.error('Erreur lors du chargement du profil:', error);
        return of(null);
      })
    ).subscribe(users => {
      if (users) {
        console.log(users);
        this.user = users;
      }
    });
  }

  logout(): void {
    this.authService.logout().subscribe({
      next: () => {
        this.router.navigate(['/']);
      },
      error: (err) => {
        console.error('Logout failed:', err);
      }
    });
  }

}
