import { apiClient } from './api';
import type { LoginRequest, RegisterRequest, AuthResponse, User } from '@/types';

class AuthServiceClass {
  async login(data: LoginRequest): Promise<AuthResponse> {
    try {
      const response = await apiClient.post<{ success: boolean; data: AuthResponse }>('/auth/login', data);
      if (response.data.success && response.data.data) {
        localStorage.setItem('auth_token', response.data.data.token);
        return response.data.data;
      }
      throw new Error('登录失败');
    } catch (error: any) {
      throw new Error(error.response?.data?.error || '登录失败');
    }
  }

  async register(data: RegisterRequest): Promise<AuthResponse> {
    try {
      const response = await apiClient.post<{ success: boolean; data: AuthResponse }>('/auth/register', data);
      if (response.data.success && response.data.data) {
        localStorage.setItem('auth_token', response.data.data.token);
        return response.data.data;
      }
      throw new Error('注册失败');
    } catch (error: any) {
      throw new Error(error.response?.data?.error || '注册失败');
    }
  }

  logout(): void {
    localStorage.removeItem('auth_token');
  }

  isAuthenticated(): boolean {
    return !!localStorage.getItem('auth_token');
  }

  getToken(): string | null {
    return localStorage.getItem('auth_token');
  }
}

export const AuthService = new AuthServiceClass();
