// auth.service.ts
import { Injectable } from '@angular/core';
import { CloudUser } from 'src/lib/ncloud';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private _currentUser: CloudUser | null = null;

  constructor(private router: Router) {
    this.initializeUser();
  }

  private async initializeUser() {
    this._currentUser = new CloudUser();
    try {
      await this._currentUser.current(); // 尝试获取当前用户
    } catch (error) {
      console.log('No logged in user');
    }
  }

  get currentUser(): CloudUser | null {
    return this._currentUser;
  }

  async getCurrentUser(): Promise<CloudUser | null> {
    if (!this._currentUser) {
      await this.initializeUser();
    }
    return this._currentUser;
  }

  async login(username: string, password: string): Promise<boolean> {
    if (!this._currentUser) {
      await this.initializeUser();
    }
    
    try {
      const user = await this._currentUser?.login(username, password);
      return !!user;
    } catch (error) {
      console.error('Login failed:', error);
      return false;
    }
  }

  async register(username: string, password: string, email?: string): Promise<boolean> {
    try {
      const newUser = new CloudUser();
      const additionalData = email ? { email } : {};
      const user = await newUser.signUp(username, password, additionalData);
      
      if (user) {
        this._currentUser = user;
        return true;
      }
      return false;
    } catch (error) {
      console.error('Registration failed:', error);
      return false;
    }
  }

  async logout(): Promise<boolean> {
    if (!this._currentUser) return true;
    
    try {
      const success = await this._currentUser.logout();
      this._currentUser = null;
      return success ?? true; // 如果 success 是 undefined，则返回 true
    } catch (error) {
      console.error('Logout failed:', error);
      return false;
    }
}

  isAuthenticated(): boolean {
    return !!this._currentUser?.sessionToken;
  }
}