import axios from 'axios'

const api = axios.create({ baseURL: 'http://localhost:8012' })

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

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

export default api

// 공통 래퍼 {success,message,data} → data 추출
const unwrap = (p: Promise<any>) => p.then(r => r.data?.data)
const qs = (o: Record<string, any>) => {
  const p = new URLSearchParams()
  Object.entries(o).forEach(([k, v]) => { if (v !== undefined && v !== null && v !== '') p.set(k, String(v)) })
  const s = p.toString()
  return s ? `?${s}` : ''
}

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

// ── Dashboard ─────────────────────────────────────────────────────────
export const getDashboardSummary = () => unwrap(api.get('/api/cms/dashboard/summary'))
export const getDashboardWorkflow = () => unwrap(api.get('/api/cms/dashboard/workflow'))
export const getTopContent = () => unwrap(api.get('/api/cms/dashboard/top-content'))

// ── Content ───────────────────────────────────────────────────────────
export const getContents = (f: { contentType?: string; status?: string; locale?: string; keyword?: string } = {}) =>
  unwrap(api.get(`/api/cms/content${qs(f)}`))
export const getContent = (id: number) => unwrap(api.get(`/api/cms/content/${id}`))
export const getContentVersions = (id: number) => unwrap(api.get(`/api/cms/content/${id}/versions`))
export const createContent = (d: object) => unwrap(api.post('/api/cms/content', d))
export const updateContent = (id: number, d: object) => unwrap(api.put(`/api/cms/content/${id}`, d))
export const deleteContent = (id: number) => api.delete(`/api/cms/content/${id}`)
export const transitionContent = (id: number, body: { action: string; note?: string; scheduledAt?: string }) =>
  unwrap(api.post(`/api/cms/content/${id}/transition`, body))
export const rollbackContent = (id: number, version: number) =>
  unwrap(api.post(`/api/cms/content/${id}/rollback`, { version }))

// ── Product ───────────────────────────────────────────────────────────
export const getProducts = (f: { status?: string; keyword?: string } = {}) =>
  unwrap(api.get(`/api/cms/product${qs(f)}`))
export const getProduct = (id: number) => unwrap(api.get(`/api/cms/product/${id}`))
export const createProduct = (d: object) => unwrap(api.post('/api/cms/product', d))
export const updateProduct = (id: number, d: object) => unwrap(api.put(`/api/cms/product/${id}`, d))
export const publishProduct = (id: number) => unwrap(api.post(`/api/cms/product/${id}/publish`))
export const productAiDraft = (topic: string, tone: string) =>
  unwrap(api.post('/api/cms/product/ai-draft', { topic, tone }))
export const productOcrExtract = (documentId: string) => unwrap(api.get(`/api/cms/product/ocr-extract/${documentId}`))
export const deleteProduct = (id: number) => api.delete(`/api/cms/product/${id}`)

// ── Banner ────────────────────────────────────────────────────────────
export const getBanners = (f: { bannerType?: string; position?: string } = {}) =>
  unwrap(api.get(`/api/cms/banner${qs(f)}`))
export const getActiveBanners = (position = '') => unwrap(api.get(`/api/cms/banner/active${position ? `?position=${position}` : ''}`))
export const getBanner = (id: number) => unwrap(api.get(`/api/cms/banner/${id}`))
export const createBanner = (d: object) => unwrap(api.post('/api/cms/banner', d))
export const updateBanner = (id: number, d: object) => unwrap(api.put(`/api/cms/banner/${id}`, d))
export const deleteBanner = (id: number) => api.delete(`/api/cms/banner/${id}`)

// ── Media ─────────────────────────────────────────────────────────────
export const getMedia = (f: { folder?: string; mediaType?: string; keyword?: string } = {}) =>
  unwrap(api.get(`/api/cms/media${qs(f)}`))
export const getMediaItem = (id: number) => unwrap(api.get(`/api/cms/media/${id}`))
export const createMedia = (d: object) => unwrap(api.post('/api/cms/media', d))
export const autoTagMedia = (id: number, imageBase64?: string) =>
  unwrap(api.post(`/api/cms/media/${id}/auto-tag`, { imageBase64 }))
export const updateMediaMeta = (id: number, meta: { altText?: string; tags?: string }) =>
  unwrap(api.put(`/api/cms/media/${id}/meta`, meta))
export const deleteMedia = (id: number) => api.delete(`/api/cms/media/${id}`)

// ── Menu ──────────────────────────────────────────────────────────────
export const getMenus = (menuType = '') => unwrap(api.get(`/api/cms/menu${menuType ? `?menuType=${menuType}` : ''}`))
export const getMenuTree = (menuType = '') => unwrap(api.get(`/api/cms/menu/tree${menuType ? `?menuType=${menuType}` : ''}`))
export const getMenu = (id: number) => unwrap(api.get(`/api/cms/menu/${id}`))
export const createMenu = (d: object) => unwrap(api.post('/api/cms/menu', d))
export const updateMenu = (id: number, d: object) => unwrap(api.put(`/api/cms/menu/${id}`, d))
export const deleteMenu = (id: number) => api.delete(`/api/cms/menu/${id}`)
export const getSitemap = (baseUrl = '') => unwrap(api.get(`/api/cms/menu/sitemap${baseUrl ? `?baseUrl=${encodeURIComponent(baseUrl)}` : ''}`))

// ── Theme ─────────────────────────────────────────────────────────────
export const getThemes = () => unwrap(api.get('/api/cms/theme'))
export const getActiveTheme = () => unwrap(api.get('/api/cms/theme/active'))
export const getTheme = (id: number) => unwrap(api.get(`/api/cms/theme/${id}`))
export const createTheme = (d: object) => unwrap(api.post('/api/cms/theme', d))
export const updateTheme = (id: number, d: object) => unwrap(api.put(`/api/cms/theme/${id}`, d))
export const activateTheme = (id: number) => unwrap(api.post(`/api/cms/theme/${id}/activate`))
export const deleteTheme = (id: number) => api.delete(`/api/cms/theme/${id}`)

// ── i18n ──────────────────────────────────────────────────────────────
export const getLocales = () => unwrap(api.get('/api/cms/i18n/locales'))
export const getResources = (locale = '') => unwrap(api.get(`/api/cms/i18n/resources${locale ? `?locale=${locale}` : ''}`))
export const createResource = (d: { locale: string; resourceKey: string; value: string }) =>
  unwrap(api.post('/api/cms/i18n/resources', d))
export const deleteResource = (id: number) => api.delete(`/api/cms/i18n/resources/${id}`)
export const translateText = (text: string, targetLocale: string) =>
  unwrap(api.post('/api/cms/i18n/translate', { text, targetLocale }))
export const translateBatch = (sourceLocale: string, targetLocale: string) =>
  unwrap(api.post('/api/cms/i18n/translate-batch', { sourceLocale, targetLocale }))

// ── SEO ───────────────────────────────────────────────────────────────
export const getSeoMetas = () => unwrap(api.get('/api/cms/seo/meta'))
export const getSeoMetaByPath = (pathKey: string, locale = '') =>
  unwrap(api.get(`/api/cms/seo/meta/by-path${qs({ pathKey, locale })}`))
export const createSeoMeta = (d: object) => unwrap(api.post('/api/cms/seo/meta', d))
export const updateSeoMeta = (id: number, d: object) => unwrap(api.put(`/api/cms/seo/meta/${id}`, d))
export const deleteSeoMeta = (id: number) => api.delete(`/api/cms/seo/meta/${id}`)
export const getRedirects = () => unwrap(api.get('/api/cms/seo/redirect'))
export const createRedirect = (d: { fromPath: string; toPath: string; statusCode: number; active: boolean }) =>
  unwrap(api.post('/api/cms/seo/redirect', d))
export const deleteRedirect = (id: number) => api.delete(`/api/cms/seo/redirect/${id}`)
export const getRobots = (baseUrl = '') => unwrap(api.get(`/api/cms/seo/robots${baseUrl ? `?baseUrl=${encodeURIComponent(baseUrl)}` : ''}`))
export const seoAiSuggest = (title: string, body: string) =>
  unwrap(api.post('/api/cms/seo/ai-suggest', { title, body }))

// ── Form ──────────────────────────────────────────────────────────────
export const getForms = () => unwrap(api.get('/api/cms/form'))
export const getForm = (id: number) => unwrap(api.get(`/api/cms/form/${id}`))
export const createForm = (d: object) => unwrap(api.post('/api/cms/form', d))
export const updateForm = (id: number, d: object) => unwrap(api.put(`/api/cms/form/${id}`, d))
export const deleteForm = (id: number) => api.delete(`/api/cms/form/${id}`)
export const submitForm = (id: number, payload: object) => unwrap(api.post(`/api/cms/form/${id}/submit`, payload))
export const getFormSubmissions = (id: number, includeSpam = false) =>
  unwrap(api.get(`/api/cms/form/${id}/submissions${includeSpam ? '?includeSpam=true' : ''}`))

// ── Channel ───────────────────────────────────────────────────────────
export const getChannels = () => unwrap(api.get('/api/cms/channel'))
export const getChannel = (id: number) => unwrap(api.get(`/api/cms/channel/${id}`))
export const createChannel = (d: { name: string; channelType: string; endpoint: string; active: boolean }) =>
  unwrap(api.post('/api/cms/channel', d))
export const updateChannel = (id: number, d: object) => unwrap(api.put(`/api/cms/channel/${id}`, d))
export const deleteChannel = (id: number) => api.delete(`/api/cms/channel/${id}`)

// ── UGC ───────────────────────────────────────────────────────────────
export const getUgc = (f: { ugcType?: string; moderationStatus?: string; targetContentId?: number } = {}) =>
  unwrap(api.get(`/api/cms/ugc${qs(f)}`))
export const getUgcQueue = () => unwrap(api.get('/api/cms/ugc/queue'))
export const getUgcItem = (id: number) => unwrap(api.get(`/api/cms/ugc/${id}`))
export const moderateUgc = (id: number, status: 'APPROVED' | 'REJECTED', reason = '') =>
  unwrap(api.put(`/api/cms/ugc/${id}/moderate`, { status, reason }))
export const getReviewSummary = (targetRef: string) =>
  unwrap(api.get(`/api/cms/ugc/review-summary${targetRef ? `?targetRef=${encodeURIComponent(targetRef)}` : ''}`))
export const deleteUgc = (id: number) => api.delete(`/api/cms/ugc/${id}`)

// ── Member ────────────────────────────────────────────────────────────
export const getMembers = (f: { segment?: string; status?: string; keyword?: string } = {}) =>
  unwrap(api.get(`/api/cms/member${qs(f)}`))
export const getMember = (id: number) => unwrap(api.get(`/api/cms/member/${id}`))
export const createMember = (d: object) => unwrap(api.post('/api/cms/member', d))
export const updateMember = (id: number, d: object) => unwrap(api.put(`/api/cms/member/${id}`, d))
export const getMemberCrmInsight = (id: number) => unwrap(api.get(`/api/cms/member/${id}/crm-insight`))
export const deleteMember = (id: number) => api.delete(`/api/cms/member/${id}`)

// ── Analytics ─────────────────────────────────────────────────────────
export const postAnalyticsEvent = (d: { contentId: number; eventType: string; amount?: number }) =>
  unwrap(api.post('/api/cms/analytics/event', d))
export const getAnalyticsTop = (limit = 10) => unwrap(api.get(`/api/cms/analytics/top?limit=${limit}`))
export const getAnalyticsContent = (id: number) => unwrap(api.get(`/api/cms/analytics/content/${id}`))
export const getAnalyticsSummary = () => unwrap(api.get('/api/cms/analytics/summary'))
export const getAnalyticsBiFeed = () => unwrap(api.get('/api/cms/analytics/bi-feed'))

// ── AI (Ollama 폴백, 항상 200) ────────────────────────────────────────
export const getAiStatus = () => unwrap(api.get('/api/cms/ai/status'))
export const aiDraft = (kind: string, topic: string, tone: string) =>
  unwrap(api.post('/api/cms/ai/draft', { kind, topic, tone }))
export const aiImageTags = (imageBase64: string, fileName: string) =>
  unwrap(api.post('/api/cms/ai/image-tags', { imageBase64, fileName }))
export const aiSeo = (title: string, body: string) => unwrap(api.post('/api/cms/ai/seo', { title, body }))
export const aiTranslate = (text: string, targetLocale: string) =>
  unwrap(api.post('/api/cms/ai/translate', { text, targetLocale }))
export const aiReviewSummary = (reviews: string[]) => unwrap(api.post('/api/cms/ai/review-summary', { reviews }))
export const aiSearchKeywords = (query: string) => unwrap(api.post('/api/cms/ai/search-keywords', { query }))
export const aiModerate = (text: string) => unwrap(api.post('/api/cms/ai/moderate', { text }))

// ── RAG (중앙 guardia-rag 최신 AI 기법 배선 — 별개 레이어, 폴백 degraded) ──
export const getRagToggles = () => unwrap(api.get('/api/cms/rag/toggles'))
export const updateRagToggle = (key: string, value: string) =>
  unwrap(api.put(`/api/cms/rag/toggles/${encodeURIComponent(key)}`, { value }))
export const ragContentDraft = (kind: string, topic: string, tone: string) =>
  unwrap(api.post('/api/cms/rag/content-draft', { kind, topic, tone }))
export const ragModerate = (text: string) => unwrap(api.post('/api/cms/rag/moderate', { text }))
export const ragFeedback = (d: { answerId?: string; query?: string; answer?: string; verdict: 'up' | 'down'; correction?: string }) =>
  unwrap(api.post('/api/cms/rag/feedback', d))

// ── Integration ───────────────────────────────────────────────────────
export const getIntegrationStatus = () => unwrap(api.get('/api/cms/integration/status'))
export const getMallProducts = () => unwrap(api.get('/api/cms/integration/mall/products'))
export const getOcrDocument = (documentId: string) => unwrap(api.get(`/api/cms/integration/ocr/${documentId}`))
export const getCrmInsight = (email: string) => unwrap(api.get(`/api/cms/integration/crm/insight?email=${encodeURIComponent(email)}`))

// ── Admin (SuperAdmin / 감사로그 Editor+) ─────────────────────────────
export const getUsers = () => api.get('/api/admin/users')
export const createUser = (data: { username: string; password: string; displayName?: string; role?: string }) =>
  api.post('/api/admin/users', data)
export const updateUserRole = (id: number, role: string) => api.put(`/api/admin/users/${id}/role`, { role })
export const updateUserActive = (id: number, active: boolean) => api.put(`/api/admin/users/${id}/active`, { active })
export const resetPassword = (id: number, password: string) => api.put(`/api/admin/users/${id}/password`, { password })
export const deleteUser = (id: number) => api.delete(`/api/admin/users/${id}`)

export const getAuditLogs = (action = '', actor = '', limit = 100) =>
  api.get(`/api/admin/audit${qs({ action, actor, limit })}`)

export const getSettings = () => api.get('/api/admin/settings')
export const updateSetting = (key: string, value: string) =>
  api.put(`/api/admin/settings/${encodeURIComponent(key)}`, { value })
