import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { isJwtExpired } from '@/utils/jwt'

const licenseClient = axios.create({
  baseURL: import.meta.env.VITE_LICENSE_API_BASE_URL ?? '',
  timeout: 15000,
})

if (import.meta.env.DEV) {
  licenseClient.interceptors.request.use((config) => {
    console.debug('[tenant-platform][License] request', {
      method: config.method?.toUpperCase(),
      url: config.baseURL ? `${config.baseURL}${config.url ?? ''}` : config.url,
      params: config.params,
    })
    return config
  })
  licenseClient.interceptors.response.use((res) => {
    console.debug('[tenant-platform][License] response', {
      status: res.status,
      url: res.config.url,
    })
    return res
  })
}

licenseClient.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token && !isJwtExpired(token)) {
    config.headers.Authorization = `Bearer ${token}`
  } else if (token && isJwtExpired(token)) {
    localStorage.removeItem('token')
    if (router.currentRoute.value.path !== '/login') {
      router.push('/login?reason=' + encodeURIComponent('登录已失效，请重新登录'))
    }
    return Promise.reject(new Error('登录已失效，请重新登录'))
  }
  return config
})

licenseClient.interceptors.response.use(
  (res) => res,
  (error) => {
    const status = error.response?.status
    if (status === 401) {
      localStorage.removeItem('token')
      if (router.currentRoute.value.path !== '/login') {
        router.push('/login')
      }
      ElMessage.error('登录已失效，请重新登录')
      return Promise.reject(error)
    }
    if (status === 403) {
      localStorage.removeItem('token')
      if (router.currentRoute.value.path !== '/login') {
        router.push('/login?reason=' + encodeURIComponent('登录已失效，请重新登录'))
      }
      ElMessage.error(error.response?.data?.message ?? '登录已失效，请重新登录')
      return Promise.reject(error)
    }
    const msg = error.response?.data?.message ?? '授权请求失败'
    ElMessage.error(msg)
    return Promise.reject(error)
  },
)

export interface AppLicense {
  id: string
  name: string
  maxDevices: number
  registeredDevices: number
  expiresAt?: string | null
  isActive: boolean
  remark?: string | null
  createdAt: string
  updatedAt: string
}

export interface LicenseDevice {
  id: string
  appKey: string
  deviceId: string
  deviceName?: string | null
  deviceModel?: string | null
  deviceVendor?: string | null
  osVersion?: string | null
  userId?: string | null
  userName?: string | null
  userEmail?: string | null
  userPhone?: string | null
  userInfoJson?: string | null
  registeredAt: string
  lastVerifiedAt?: string | null
  isActive: boolean
  createdAt: string
}

export const licenseApi = {
  getAppLicense(appKey: string) {
    return licenseClient.get<{ data: { license: AppLicense; devices: LicenseDevice[] } }>(
      `/api/license/admin/apps/${encodeURIComponent(appKey)}`,
    )
  },

  updateAppLicense(appKey: string, data: { maxDevices?: number; isActive?: boolean; remark?: string; expiresAt?: string }) {
    return licenseClient.patch<{ data: AppLicense }>(
      `/api/license/admin/apps/${encodeURIComponent(appKey)}`,
      data,
    )
  },

  revokeDevice(id: string) {
    return licenseClient.delete<{ data: null }>(`/api/license/admin/devices/${encodeURIComponent(id)}`)
  },

  reactivateDevice(id: string) {
    return licenseClient.put<{ data: null }>(`/api/license/admin/devices/${encodeURIComponent(id)}/reactivate`)
  },
}
