import { apiClient } from './client';
import { LoginDto, RegisterDto, AuthResponse, ApiResponse, UserResponse } from '@goodgo/types';

export const authApi = {
  register: async (data: RegisterDto): Promise<ApiResponse<AuthResponse>> => {
    return apiClient.post('/auth/register', data);
  },

  login: async (data: LoginDto): Promise<ApiResponse<AuthResponse>> => {
    const response = await apiClient.post('/auth/login', data);
    if (response.success && response.data) {
      apiClient.setAuthToken(response.data.accessToken);
      if (typeof window !== 'undefined') {
        localStorage.setItem('refreshToken', response.data.refreshToken);
      }
    }
    return response;
  },

  logout: async (): Promise<ApiResponse> => {
    const refreshToken = typeof window !== 'undefined' ? localStorage.getItem('refreshToken') : null;
    const response = await apiClient.post('/auth/logout', { refreshToken });
    apiClient.removeAuthToken();
    if (typeof window !== 'undefined') {
      localStorage.removeItem('refreshToken');
    }
    return response;
  },

  refreshToken: async (refreshToken: string): Promise<ApiResponse<{ accessToken: string }>> => {
    const response = await apiClient.post('/auth/refresh', { refreshToken });
    if (response.success && response.data) {
      apiClient.setAuthToken(response.data.accessToken);
    }
    return response;
  },

  getMe: async (): Promise<ApiResponse<UserResponse>> => {
    return apiClient.get('/users/me');
  },

  changePassword: async (currentPassword: string, newPassword: string): Promise<ApiResponse> => {
    return apiClient.put('/auth/password', { currentPassword, newPassword });
  },
};
