import axios from 'axios'

const api = axios.create({ baseURL: '' })

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

api.interceptors.response.use(
  res => res,
  err => {
    if (err.response?.status === 401) {
      localStorage.removeItem('esn_token')
      if (location.pathname !== '/login') location.href = '/login'
    }
    return Promise.reject(err)
  }
)

export default api

const unwrap = (p: Promise<any>) => p.then(r => r.data?.data)

// ── Auth ──────────────────────────────────────────────────────────────────
export const login  = (username: string, password: string) =>
  api.post('/api/auth/login', { username, password })
export const getMe  = () => api.get('/api/auth/me')
export const logout = () => api.post('/api/auth/logout')

// ── WISE AI (중앙 guardia-rag /rag/answer 프록시) ──────────────────────────
export const wiseAsk = (query: string) => unwrap(api.post('/api/wise/ask', { query }))

// ── Dashboard ────────────────────────────────────────────────────────────
export const getDashboard = (tenantCode?: string) =>
  unwrap(api.get(`/api/dashboard${tenantCode ? `?tenantCode=${tenantCode}` : ''}`))

// ── Tenants ──────────────────────────────────────────────────────────────
export const getTenants    = ()           => unwrap(api.get('/api/tenants'))
export const createTenant  = (d: object)  => unwrap(api.post('/api/tenants', d))
export const updateTenant  = (id: number, d: object) => unwrap(api.put(`/api/tenants/${id}`, d))
export const deleteTenant  = (id: number) => api.delete(`/api/tenants/${id}`)

// ── Stores ───────────────────────────────────────────────────────────────
export const getStores  = (params?: object) => unwrap(api.get('/api/stores', { params }))
export const getStore   = (id: number)       => unwrap(api.get(`/api/stores/${id}`))
export const createStore = (d: object)       => unwrap(api.post('/api/stores', d))
export const updateStore = (id: number, d: object) => unwrap(api.put(`/api/stores/${id}`, d))
export const deleteStore = (id: number)       => api.delete(`/api/stores/${id}`)

// ── Store Groups ─────────────────────────────────────────────────────────
export const getStoreGroups  = (tenantCode?: string) =>
  unwrap(api.get('/api/store-groups', { params: { tenantCode } }))
export const createStoreGroup = (d: object)  => unwrap(api.post('/api/store-groups', d))
export const updateStoreGroup = (id: number, d: object) => unwrap(api.put(`/api/store-groups/${id}`, d))
export const deleteStoreGroup = (id: number) => api.delete(`/api/store-groups/${id}`)

// ── Templates ────────────────────────────────────────────────────────────
export const getTemplates   = (params?: object) => unwrap(api.get('/api/templates', { params }))
export const createTemplate = (d: object)        => unwrap(api.post('/api/templates', d))
export const updateTemplate = (id: number, d: object) => unwrap(api.put(`/api/templates/${id}`, d))
export const deleteTemplate = (id: number)        => api.delete(`/api/templates/${id}`)

// ── POS CVT ──────────────────────────────────────────────────────────────
export const getPosCvt     = (params?: object) => unwrap(api.get('/api/pos-cvt', { params }))
export const processPosCvt = (id: number)       => unwrap(api.put(`/api/pos-cvt/${id}/process`))
export const ignorePosCvt  = (id: number)       => unwrap(api.put(`/api/pos-cvt/${id}/ignore`))

// ── Alarms ───────────────────────────────────────────────────────────────
export const getAlarms    = (params?: object) => unwrap(api.get('/api/alarms', { params }))
export const createAlarm  = (d: object)        => unwrap(api.post('/api/alarms', d))
export const resolveAlarm = (id: number, resolution: string) =>
  unwrap(api.put(`/api/alarms/${id}/resolve`, { resolution }))
export const deleteAlarm  = (id: number) => api.delete(`/api/alarms/${id}`)

// ── HCore ────────────────────────────────────────────────────────────────
export const getHCore        = (params?: object)  => unwrap(api.get('/api/hcore', { params }))
export const updateHCoreStatus = (id: number, status: string) =>
  unwrap(api.put(`/api/hcore/${id}/status`, { status }))

// ── Works ────────────────────────────────────────────────────────────────
export const getWorks   = (params?: object)  => unwrap(api.get('/api/works', { params }))
export const createWork = (d: object)         => unwrap(api.post('/api/works', d))
export const updateWork = (id: number, d: object) => unwrap(api.put(`/api/works/${id}`, d))
export const deleteWork = (id: number)         => api.delete(`/api/works/${id}`)

// ── Firmware ─────────────────────────────────────────────────────────────
export const getFirmware   = (params?: object) => unwrap(api.get('/api/firmware', { params }))
export const createFirmware = (d: object)       => unwrap(api.post('/api/firmware', d))
export const deleteFirmware = (id: number)      => api.delete(`/api/firmware/${id}`)

// ── Users ────────────────────────────────────────────────────────────────
export const getUsers   = (params?: object)  => unwrap(api.get('/api/users', { params }))
export const createUser = (d: object)         => unwrap(api.post('/api/users', d))
export const updateUser = (id: number, d: object) => unwrap(api.put(`/api/users/${id}`, d))
export const deleteUser = (id: number)         => api.delete(`/api/users/${id}`)

// ── Products ─────────────────────────────────────────────────────────────
export const getProducts   = (params?: object) => unwrap(api.get('/api/products', { params }))
export const createProduct = (d: object)        => unwrap(api.post('/api/products', d))
export const updateProduct = (id: number, d: object) => unwrap(api.put(`/api/products/${id}`, d))
export const deleteProduct = (id: number)        => api.delete(`/api/products/${id}`)

// ── AI ───────────────────────────────────────────────────────────────────
export const analyzeAlarm = (d: object)  => unwrap(api.post('/api/ai/analyze-alarm', d))
export const classifyPos  = (d: object)  => unwrap(api.post('/api/ai/classify-pos', d))
export const aiChat       = (message: string) => unwrap(api.post('/api/ai/chat', { message }))
