import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { useUserStore } from '@/stores/user'

const http = axios.create({
  baseURL: '/api',
  timeout: 15000,
})

http.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
})

http.interceptors.response.use(
  res => res.data,
  err => {
    if (err.response?.status === 401) {
      localStorage.removeItem('token')
      const userStore = useUserStore()
      userStore.reset()
      // _noRedirect 标记：静默验证时不跳转（避免注册/登录页被重定向）
      if (!err.config?._noRedirect) {
        router.push('/login')
      }
      return Promise.reject(err)
    }
    // 支持静默模式：config._silent=true 时不弹出错误提示
    if (!err.config?._silent) {
      const msg = err.response?.data?.error || '请求失败'
      ElMessage.error(msg)
    }
    return Promise.reject(err)
  }
)

// Auth
export const auth = {
  register: data => http.post('/auth/register', data),
  login: data => http.post('/auth/login', data),
  logout: () => http.post('/auth/logout'),
  profile: () => http.get('/auth/profile'),
  profileSilent: () => http.get('/auth/profile', { _silent: true, _noRedirect: true }),
  captcha: () => http.get('/auth/captcha'),
  wechatLoginUrl: () => http.get('/auth/wechat/login'),
}

// Works
export const works = {
  list: params => http.get('/works', { params }),
  create: data => http.post('/works', data),
  get: id => http.get(`/works/${id}`),
  update: (id, data) => http.put(`/works/${id}`, data),
  delete: id => http.delete(`/works/${id}`),
}

// Payment
export const payment = {
  createOrder: planType => http.post('/payment/create-order', { plan_type: planType }),
  getOrder: orderNo => http.get(`/payment/order/${orderNo}`),
  orders: () => http.get('/payment/my-orders'),
  checkResult: orderNo => http.get(`/payment/result/${orderNo}`, { _silent: true }),
}

// Product (商品管理)
export const product = {
  list: () => http.get('/product/list'),              // 前端公开：启用商品列表
  buy: (productId, data) => http.post(`/product/${productId}/buy`, data),  // 购买商品
  // 管理端接口（需登录token）
  adminList: params => http.get('/product', { params }),     // 分页列表
  get: id => http.get(`/product/${id}`),
  create: data => http.post('/product', data),
  update: (id, data) => http.put(`/product/${id}`, data),
  delete: id => http.delete(`/product/${id}`),
  toggle: id => http.post(`/product/${id}/toggle`),
}

// Public
export const publicApi = {
  banners: () => http.get('/public/banners'),
}

export default { auth, works, payment, product, public: publicApi }
