import axios from 'axios'
import { handleSessionExpired } from './handleSessionExpired'
import { createDiscreteApi } from 'naive-ui'
import { t } from '../i18n'

// 创建独立的 Naive UI message API（可在非 setup 上下文中使用）
const { message } = createDiscreteApi(['message'])

// 清理 HTML 标签，将 HTML 转换为纯文本
function stripHtmlTags(html: string): string {
  if (!html) return html
  
  // 创建临时 DOM 元素来解析 HTML
  const temp = document.createElement('div')
  temp.innerHTML = html
  
  // 获取纯文本内容
  return temp.textContent || temp.innerText || html
}

/**
 * 配置 axios 全局拦截器
 * 1. 请求拦截器：为所有非 GET 请求自动添加 CSRF token
 * 2. 响应拦截器：统一处理 HTTP 错误（401, 403, 404, 413, 417, 508 等），显示友好提示
 */

axios.interceptors.request.use(
  (config) => {
    const csrfToken = (window as any).jingrow?.csrf_token
    
    if (csrfToken && config.method && config.method.toLowerCase() !== 'get') {
      config.headers['X-Jingrow-CSRF-Token'] = csrfToken
    }
    
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  (response) => response,
  async (error) => {
    
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          // 会话过期，自动退出登录
          await handleSessionExpired(status)
          break
          
        case 403: {
          // 权限不足
          let errorMessage = t('You do not have enough permissions to access this resource. Please contact your manager to get access.')
          
          // 优先使用后端返回的错误消息
          if (data?._error_message) {
            errorMessage = stripHtmlTags(data._error_message)
          } else if (data?._server_messages) {
            try {
              const serverMessages = JSON.parse(data._server_messages)
              if (Array.isArray(serverMessages) && serverMessages.length > 0) {
                // 解析 server message（可能是 JSON 字符串）
                const firstMessage = JSON.parse(serverMessages[0])
                if (firstMessage.message) {
                  errorMessage = stripHtmlTags(firstMessage.message)
                }
              }
            } catch (e) {
              // 解析失败，使用默认消息
            }
          }
          
          message.error(errorMessage, {
            duration: 5000,
            closable: true
          })
          break
        }
          
        case 404:
          // 资源不存在
          message.error(t('The resource you are looking for is not available'), {
            duration: 3000,
            closable: true
          })
          break
          
        case 413:
          // 文件过大
          const maxSize = ((window as any).jingrow?.boot?.max_file_size || 5242880) / 1048576
          message.error(t('File size exceeded the maximum allowed size of {0} MB', { 0: maxSize.toString() }), {
            duration: 5000,
            closable: true
          })
          break
          
        case 417: {
          // 期望失败（通常是验证错误）
          let errorMsg = t('Operation failed, please check your input')
          if (data?.message) {
            errorMsg = data.message
          } else if (data?._server_messages) {
            try {
              const serverMessages = JSON.parse(data._server_messages)
              if (Array.isArray(serverMessages) && serverMessages.length > 0) {
                const firstMessage = JSON.parse(serverMessages[0])
                if (firstMessage.message) {
                  errorMsg = firstMessage.message
                }
              }
            } catch (e) {
              // 解析失败，使用默认消息
            }
          } else if (data?.exc) {
            // 解析异常信息
            try {
              const excLines = data.exc.split('\n')
              const lastLine = excLines[excLines.length - 1] || excLines[excLines.length - 2]
              if (lastLine) {
                errorMsg = lastLine.trim()
              }
            } catch (e) {
              // 解析失败，使用默认消息
            }
          }
          message.error(errorMsg, {
            duration: 5000,
            closable: true
          })
          break
        }
          
        case 508:
          // 事务冲突
          message.warning(t('Another transaction is blocking this one. Please try again in a few seconds.'), {
            duration: 5000,
            closable: true
          })
          break
          
        default:
          // 其他错误，显示通用消息或后端返回的消息
          if (data?.message) {
            message.error(data.message, {
              duration: 5000,
              closable: true
            })
          } else if (data?._server_messages) {
            try {
              const serverMessages = JSON.parse(data._server_messages)
              if (Array.isArray(serverMessages) && serverMessages.length > 0) {
                const firstMessage = JSON.parse(serverMessages[0])
                message.error(firstMessage.message || t('Operation failed'), {
                  duration: 5000,
                  closable: true
                })
              }
            } catch (e) {
              message.error(t('Request failed') + ` (${status})`, {
                duration: 3000,
                closable: true
              })
            }
          } else {
            message.error(t('Request failed') + ` (${status})`, {
              duration: 3000,
              closable: true
            })
          }
      }
    } else if (error.request) {
      // 请求已发送但没有收到响应（网络错误）
      message.error(t('Network connection failed, please check your network connection'), {
        duration: 5000,
        closable: true
      })
    } else {
      // 其他错误
      message.error(error.message || t('Unknown error'), {
        duration: 3000,
        closable: true
      })
    }
    
    return Promise.reject(error)
  }
)

export default axios
