import api, { ApiResponse } from './api';

// Types
export interface LoginRequest {
  email: string;
  password: string;
}

export interface AuthUser {
  id: string;
  email: string;
  role: string;
  firstName: string;
  lastName: string;
  avatar: string | null;
}

export interface AuthResponse {
  user: AuthUser;
  accessToken: string;
  refreshToken: string;
}

export interface MessageResponse {
  message: string;
}

// Auth Service
class AuthService {
  private basePath = '/auth';

  async login(data: LoginRequest): Promise<AuthResponse> {
    const response = await api.post<ApiResponse<AuthResponse>>(
      `${this.basePath}/login`,
      data
    );

    const authData = response.data.data;

    // Check if user is ADMIN or SUPER_ADMIN
    if (authData.user.role !== 'ADMIN' && authData.user.role !== 'SUPER_ADMIN') {
      throw new Error('Access denied. Admin privileges required.');
    }

    // Store tokens and user
    localStorage.setItem('accessToken', authData.accessToken);
    localStorage.setItem('refreshToken', authData.refreshToken);
    localStorage.setItem('user', JSON.stringify(authData.user));

    return authData;
  }

  async logout(): Promise<void> {
    try {
      await api.post<ApiResponse<MessageResponse>>(`${this.basePath}/logout`);
    } finally {
      localStorage.removeItem('accessToken');
      localStorage.removeItem('refreshToken');
      localStorage.removeItem('user');
    }
  }

  async getCurrentUser(): Promise<AuthUser> {
    const response = await api.get<ApiResponse<AuthUser>>(`${this.basePath}/me`);
    return response.data.data;
  }

  async refreshToken(): Promise<{ accessToken: string; refreshToken: string }> {
    const refreshToken = localStorage.getItem('refreshToken');
    if (!refreshToken) {
      throw new Error('No refresh token available');
    }

    const response = await api.post<ApiResponse<{ accessToken: string; refreshToken: string }>>(
      `${this.basePath}/refresh`,
      { refreshToken }
    );

    const tokens = response.data.data;
    localStorage.setItem('accessToken', tokens.accessToken);
    localStorage.setItem('refreshToken', tokens.refreshToken);

    return tokens;
  }

  // Get stored user from localStorage
  getStoredUser(): AuthUser | null {
    if (typeof window === 'undefined') return null;

    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      try {
        return JSON.parse(storedUser);
      } catch {
        return null;
      }
    }
    return null;
  }

  // Check if user is authenticated
  isAuthenticated(): boolean {
    if (typeof window === 'undefined') return false;
    return !!localStorage.getItem('accessToken');
  }

  // Clear auth data
  clearAuth(): void {
    localStorage.removeItem('accessToken');
    localStorage.removeItem('refreshToken');
    localStorage.removeItem('user');
  }
}

export const authService = new AuthService();
