import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {environment} from "../../environments/environment";

interface UserInfo {
  userId: number;
  username: string;
}

@Injectable({
  providedIn: 'root'
})
export class UserService {

  currentUser: UserInfo | null = null;

  loginCallback: () => void = () => {};

  constructor(private httpClient: HttpClient) {
    this.currentUser = this.loadCurrentUserFromLocalStorage();
    this.updateUser()
      .catch(reason => console.debug(reason));
  }

  isUserLoggedIn(): boolean {
    return this.currentUser !== null;
  }

  public updateUser(): Promise<any> {
    return new Promise((resolve, reject) => {
      this.httpClient.get<UserInfo>(`${environment.apiUrl}/auth`)
        .subscribe({
          next: (user) => {
            this.currentUser = user;
            this.saveCurrentUserToLocalStorage(user);
            this.loginCallback();
            resolve(user);
          },
          error: (err) => {
            if (err.status === 401) {
              this.currentUser = null;
              this.clearCurrentUserFromLocalStorage();
            }
            reject(err);
          }
        });
    });
  }

  public getLoginUrl(): string {
    return `${environment.apiUrl}/oauth2/authorization/osu`
  }

  public getLogoutUrl(): string {
    return `${environment.apiUrl}/logout`
  }

  saveCurrentUserToLocalStorage(user: UserInfo) {
    localStorage.setItem('currentUser', JSON.stringify(user));
  }

  loadCurrentUserFromLocalStorage(): UserInfo {
    const savedUser = localStorage.getItem('currentUser');
    return savedUser ? JSON.parse(savedUser) : null;
  }

  clearCurrentUserFromLocalStorage() {
    localStorage.removeItem('currentUser');
    document.cookie = 'SESSION=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
  }

}
