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

const API_BASE_URL = '/api'

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  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 questionAPI = {
  pageQuestions: (params = {}) => {
    return apiClient.get('/question/page', { params })
  },

  getQuestionById: (id) => {
    return apiClient.get(`/question/${id}`)
  },

  getPendingQuestions: () => {
    return apiClient.get('/question/pending')
  },

  getQuestionsByDocumentName: (documentName, limit = 50) => {
    return apiClient.get('/question/list', {
      params: { documentName, limit }
    })
  },

  getQuestionsByDocumentId: (documentId, limit = 50) => {
    return apiClient.get('/question/list', {
      params: { limit }
    }).then(response => {
      if (response.data && response.data.data) {
        const filtered = response.data.data.filter(
          q => q.documentId === documentId || String(q.documentId) === String(documentId)
        )
        return { ...response.data, data: filtered }
      }
      return response.data
    })
  },

  reviewQuestion: (questionId, status, reviewerComment) => {
    const params = { status, reviewerComment: reviewerComment || '' }
    return apiClient.put(`/question/review/${questionId}`, null, { params })
  },

  deleteQuestion: (id) => {
    return apiClient.delete(`/question/${id}`)
  },

  updateQuestion: (id, data) => {
    return apiClient.put(`/question/${id}`, data)
  }
}

export default questionAPI
