import { useAuthStore } from '@/stores/authStore';
import type {
  AddChatRoomMemberRequest,
  ApiResponse,
  CreateChatRoomRequest,
  LoginRequest,
  RegisterRequest,
  RemoveChatRoomMemberRequest,
  UpdateChatRoomRequest,
  UpdateUserRequest,
} from '@/types';
import axios, { type AxiosResponse } from 'axios';

const API_BASE_URL =
  import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api';

const api = axios.create({
  baseURL: API_BASE_URL,
});

api.interceptors.request.use((config) => {
  const token = useAuthStore.getState().token;
  if (token) config.headers.Authorization = `Bearer ${token}`;

  return config;
});

api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      useAuthStore.getState().logout();
    }

    return Promise.reject(error);
  }
);

export const authAPI = {
  login: (data: LoginRequest): Promise<AxiosResponse<ApiResponse>> =>
    api.post('/auth/login', data),
  register: (data: RegisterRequest): Promise<AxiosResponse<ApiResponse>> =>
    api.post('/auth/register', data),
};

export const chatAPI = {
  getChatRooms: (): Promise<AxiosResponse<ApiResponse>> =>
    api.get('/chat-rooms'),
  createChatRoom: (
    data: CreateChatRoomRequest
  ): Promise<AxiosResponse<ApiResponse>> => api.post('/chat-rooms', data),
  getMessages: (
    roomId: string,
    page = 1,
    limit = 50
  ): Promise<AxiosResponse<ApiResponse>> =>
    api.get(`/messages/${roomId}?page=${page}&limit=${limit}`),
  updateChatRoom: (
    roomId: string,
    data: UpdateChatRoomRequest
  ): Promise<AxiosResponse<ApiResponse>> =>
    api.put(`/chat-rooms/${roomId}`, data),
  deleteChatRoom: (roomId: string): Promise<AxiosResponse<ApiResponse>> =>
    api.delete(`/chat-rooms/${roomId}`),
  addChatRoomMember: (
    roomId: string,
    data: AddChatRoomMemberRequest
  ): Promise<AxiosResponse<ApiResponse>> =>
    api.post(`/chat-rooms/${roomId}/members`, data),
  removeChatRoomMember: (
    roomId: string,
    data: RemoveChatRoomMemberRequest
  ): Promise<AxiosResponse<ApiResponse>> =>
    api.delete(`/chat-rooms/${roomId}/members`, { data }),
};

export const userAPI = {
  updateProfile: (
    data: UpdateUserRequest
  ): Promise<AxiosResponse<ApiResponse>> => api.put('/users/profile', data),
};

export default api;
