import axios from 'axios'


const BASE_URL = 'https://cinema.kolei.ru'

const api = axios.create({
  baseURL: BASE_URL,
  headers: {
    'Content-Type': 'application/json'
  }
})

// Добавляем токен к каждому запросу
api.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// Экспортируем authAPI как константу
export const authAPI = {
  login: async (email, password) => {
    try {
      const response = await api.post('/auth/login', {
        email,
        password
      })

      if (response.data.token) {
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('userData', JSON.stringify({
          firstName: response.data.firstName,
          lastName: response.data.lastName,
          email: response.data.email
        }))
      }
      return response.data
    } catch (error) {
      console.log(error)
    }
  },

  register: async (userData) => {
    try {
      const response = await api.post('/auth/register', {
        firstName: userData.firstName,
        lastName: userData.lastName,
        email: userData.email,
        password: userData.password
      })
      return response.data
    } catch (error) {
      console.log(error)
    }
  },

  getFilePath: (fileName) => {
    return `${BASE_URL}/up/images/${fileName}`
  },

  getUserData: async () => {
    try {
      const response = await api.get('/user');
      return response.data
    } catch (error) {
      console.error('Ошибка при получении данных пользователя:', error)
    }
  },

  uploadFile: async (file) => {
    const token = localStorage.getItem('token')

    const formData = new FormData()
    formData.append('file', file)
    formData.append('token', token)

    try {
      const response = await api.post('/user/avatar', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      return response.data;
    } catch (error) {
      alert('Ошибка при загрузке аватара')
      console.error('Ошибка загрузки:', error)
    }
  },

  logout: () => {
    localStorage.removeItem('token')
  }
}

export default api

