import axios from 'axios'

// GUARDiA Signage 프론트 API 클라이언트. ApiResponse 봉투({ success, message, data }) → data 언랩.
const api = axios.create({ baseURL: '' })

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

api.interceptors.response.use(
  res => res,
  err => {
    if (err.response?.status === 401) {
      localStorage.removeItem('sgn_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 (2FA 지원: login 응답 twofa=='true' 이면 verify 필요) ──────────────
export const login = (username: string, password: string) =>
  api.post('/api/auth/login', { username, password })
export const verify2fa = (verifyToken: string, code: string) =>
  api.post('/api/auth/verify', { verifyToken, code })
export const getMe = () => api.get('/api/auth/me')
export const logout = () => api.post('/api/auth/logout')

// ── Dashboard ──────────────────────────────────────────────────────────────
export const getDashboard = (tenantCode?: string) =>
  unwrap(api.get('/api/dashboard', { params: 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}`)

// ── Regions (지역: 서울/대전/대구/부산) ──────────────────────────────────────
export const getRegions   = (params?: object)      => unwrap(api.get('/api/regions', { params }))
export const createRegion = (d: object)            => unwrap(api.post('/api/regions', d))
export const updateRegion = (id: number, d: object) => unwrap(api.put(`/api/regions/${id}`, d))
export const deleteRegion = (id: number)           => api.delete(`/api/regions/${id}`)

// ── Stores ─────────────────────────────────────────────────────────────────
export const getStores   = (params?: object)       => unwrap(api.get('/api/stores', { params }))
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}`)

// ── 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 setUserActive = (id: number, active: boolean) => unwrap(api.put(`/api/users/${id}/active`, { active }))
export const deleteUser  = (id: number)            => api.delete(`/api/users/${id}`)

// ── Gateways (GEN1/GEN2/GEN2_PLUS_EMS) ───────────────────────────────────────
export const getGateways   = (params?: object)     => unwrap(api.get('/api/gateways', { params }))
export const createGateway = (d: object)           => unwrap(api.post('/api/gateways', d))
export const updateGateway = (id: number, d: object) => unwrap(api.put(`/api/gateways/${id}`, d))
export const setGatewayStatus = (id: number, status: string) => api.put(`/api/gateways/${id}/status`, { status })
export const deleteGateway = (id: number)          => api.delete(`/api/gateways/${id}`)

// ── SignBoards (ESB 태그 패널) ───────────────────────────────────────────────
export const getSignBoards = (params?: object)     => unwrap(api.get('/api/signboards', { params }))
export const bindSignBoard = (d: object)           => unwrap(api.post('/api/signboards', d))
export const updateSignBoard = (id: number, d: object) => unwrap(api.put(`/api/signboards/${id}`, d))
export const unbindSignBoard = (id: number)        => api.put(`/api/signboards/${id}/unbind`)

// ── Templates (Template / Font / Image Code) ────────────────────────────────
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}`)

// ── Template Groups (일괄배포 단위) ─────────────────────────────────────────
export const getTemplateGroups   = (params?: object) => unwrap(api.get('/api/template-groups', { params }))
export const createTemplateGroup = (d: object)       => unwrap(api.post('/api/template-groups', d))
export const updateTemplateGroup = (id: number, d: object) => unwrap(api.put(`/api/template-groups/${id}`, d))
export const deleteTemplateGroup = (id: number)      => api.delete(`/api/template-groups/${id}`)

// ── Sign Images (간판 이미지 코드) ──────────────────────────────────────────
export const getSignImages   = (params?: object)   => unwrap(api.get('/api/sign-images', { params }))
export const createSignImage = (d: object)         => unwrap(api.post('/api/sign-images', d))
export const updateSignImage = (id: number, d: object) => unwrap(api.put(`/api/sign-images/${id}`, d))
export const deleteSignImage = (id: number)        => api.delete(`/api/sign-images/${id}`)

// ── Sign Deploys (간판정보 CSV → 매장코드 중앙배포, 30초 폴링) ──────────────
export const getSignDeploys   = (params?: object)  => unwrap(api.get('/api/sign-deploys', { params }))
export const createSignDeploy = (d: object)        => unwrap(api.post('/api/sign-deploys', d))
export const updateSignDeploy = (id: number, d: object) => unwrap(api.put(`/api/sign-deploys/${id}`, d))
export const deleteSignDeploy = (id: number)       => api.delete(`/api/sign-deploys/${id}`)

// ── Firmware (eESB / GW / Tag FW 배포) ──────────────────────────────────────
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}`)

// ── Backups (매장코드별 일일 백업/복구) ─────────────────────────────────────
export const getBackups   = (params?: object)      => unwrap(api.get('/api/backups', { params }))
export const createBackup = (d: object)            => unwrap(api.post('/api/backups', d))
export const updateBackup = (id: number, d: object) => unwrap(api.put(`/api/backups/${id}`, d))
export const deleteBackup = (id: number)           => api.delete(`/api/backups/${id}`)

// ── Ad Schedules (광고/스케줄 편성) ─────────────────────────────────────────
export const getAdSchedules   = (params?: object)  => unwrap(api.get('/api/ad-schedules', { params }))
export const createAdSchedule = (d: object)        => unwrap(api.post('/api/ad-schedules', d))
export const updateAdSchedule = (id: number, d: object) => unwrap(api.put(`/api/ad-schedules/${id}`, d))
export const deleteAdSchedule = (id: number)       => api.delete(`/api/ad-schedules/${id}`)

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

// ── Admin: 감사 로그 / 시스템 설정 ──────────────────────────────────────────
export const getAuditLogs  = (params?: object)     => unwrap(api.get('/api/admin/audit', { params }))
export const getAuditCount = (params?: object)     => unwrap(api.get('/api/admin/audit/count', { params }))
export const getSettings   = (category?: string)   => unwrap(api.get('/api/admin/settings', { params: category ? { category } : {} }))
export const updateSetting = (key: string, value: string) => unwrap(api.put(`/api/admin/settings/${encodeURIComponent(key)}`, { value }))

// ── AI (온프레미스/Claude AiTextRouter) ──────────────────────────────────────
export const aiAnalyzeAlarm   = (d: object)        => unwrap(api.post('/api/ai/analyze-alarm', d))
export const aiGenerateSignText = (d: object)      => unwrap(api.post('/api/ai/generate-sign-text', d))
export const aiRecommendAd    = (d: object)        => unwrap(api.post('/api/ai/recommend-ad', d))
export const aiChat           = (message: string)  => unwrap(api.post('/api/ai/chat', { message }))
