// 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 initializeUser() {
    this.currentUser = new CloudUser();
  }

  // 获取当前用户
  async getCurrentUser() {
    if (!this.currentUser) {
      this.initializeUser();
    }
    return await this.currentUser?.current();
  }

  // 用户登录
  async login(username: string, password: string): Promise<boolean> {
    try {
      const user = await this.currentUser?.login(username, password);
      if (user) {
        return true;
      }
      return false;
    } catch (error) {
      console.error('登录失败:', error);
      return false;
    }
  }

  // 用户注册
  async register(username: string, password: string, email?: string): Promise<boolean> {
    try {
      const additionalData = email ? { email } : {};
      const user = await this.currentUser?.signUp(username, password, additionalData);
      return !!user;
    } catch (error) {
      console.error('注册失败:', error);
      return false;
    }
  }

  // 用户登出
  async logout(): Promise<boolean> {
    try {
      const success = await this.currentUser?.logout();
      if (success) {
        this.currentUser = null;
        this.router.navigate(['/login']);
      }
      return !!success;
    } catch (error) {
      console.error('登出失败:', error);
      return false;
    }
  }

  // 检查是否已登录
  isAuthenticated(): boolean {
    return !!this.currentUser?.sessionToken;
  }
}