import axios from 'axios'
import { handleAuthError } from './auth.js'

const API_BASE_URL = '/api'

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json'
  }
})

apiClient.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => Promise.reject(error)
)

apiClient.interceptors.response.use(
  response => response,
  error => {
    const status = error.response?.status
    if (status === 401 || status === 403) {
      handleAuthError()
      return Promise.reject(error)
    }
    return Promise.reject(error)
  }
)

export const imageAPI = {
  getImageData: (imageId) => {
    return apiClient.get(`/image/${imageId}/data`, {
      responseType: 'blob'
    })
  },

  getImageInfo: (imageId) => {
    return apiClient.get(`/image/${imageId}/info`)
  },

  getImagesBySession: (sessionId, params = {}) => {
    return apiClient.get(`/image/session/${sessionId}`, { params })
  },

  getImagesByFile: (fileId, params = {}) => {
    return apiClient.get(`/image/file/${fileId}`, { params })
  },

  downloadImage: (imageId) => {
    return apiClient.get(`/image/${imageId}/download`, {
      responseType: 'blob'
    })
  },

  deleteImage: (imageId) => {
    return apiClient.delete(`/image/${imageId}`)
  }
}

export default imageAPI
