import http from './http'
import { demo, demoApi } from '@/demo'

// 백엔드 /api/account 엔드포인트와 매핑 (본인 데이터만)
const realApi = {
  list({ year, month, type, category, walletId, keyword, tagId } = {}) {
    return http.get('/account/entries', { params: { year, month, type, category, walletId, keyword, tagId } })
  },
  summary({ year, month } = {}) {
    return http.get('/account/summary', { params: { year, month } })
  },
  stats({ unit, year, month } = {}) {
    return http.get('/account/stats', { params: { unit, year, month } })
  },
  categoryStats({ type, year, month } = {}) {
    return http.get('/account/category-stats', { params: { type, year, month } })
  },
  // 통계 화면 집계 → AI 재무 코멘트(유료). 실패해도 화면을 막지 않도록 전역 배너 억제
  aiComment(payload) {
    return http.post('/account/ai-comment', payload, { timeout: 30000, suppressNetError: true })
  },
  netWorthTrend({ months, weeks, unit } = {}) {
    return http.get('/account/networth/trend', { params: { months, weeks, unit } })
  },
  create(payload) {
    return http.post('/account/entries', payload)
  },
  update(id, payload) {
    return http.put(`/account/entries/${id}`, payload)
  },
  remove(id) {
    return http.delete(`/account/entries/${id}`)
  },
  // 문자/푸시 텍스트 파싱(저장 안 함) → 추가 폼 자동채움
  // categoryHints/walletHints: AI가 이 후보들 중에서 분류·결제수단을 고르도록 사용자 목록 전달
  parseText({ title, text, categoryHints, walletHints } = {}) {
    return http.post('/account/entries/parse', { title, text, categoryHints, walletHints })
  },
  // 환율 조회 — 외화 결제 입력 시 통화→원화 환율 자동 채움
  fxRate(from, to = 'KRW') {
    return http.get('/fx/rate', { params: { from, to } })
  },

  // 자주 쓰는 내역(빠른 등록 템플릿)
  quickEntries() {
    return http.get('/account/quick-entries')
  },
  createQuickEntry(payload) {
    return http.post('/account/quick-entries', payload)
  },
  removeQuickEntry(id) {
    return http.delete(`/account/quick-entries/${id}`)
  },

  // 계좌/카드 (사용자별)
  wallets() {
    return http.get('/account/wallets')
  },
  netWorth() {
    return http.get('/account/networth')
  },
  repayment(payload) {
    return http.post('/account/repayment', payload)
  },

  // 정기/반복 거래
  recurrings() {
    return http.get('/account/recurrings')
  },
  createRecurring(payload) {
    return http.post('/account/recurrings', payload)
  },
  updateRecurring(id, payload) {
    return http.put(`/account/recurrings/${id}`, payload)
  },
  removeRecurring(id) {
    return http.delete(`/account/recurrings/${id}`)
  },
  runRecurrings() {
    return http.post('/account/recurrings/run')
  },

  // 예산 (사용자별)
  budgets({ year, month } = {}) {
    return http.get('/account/budgets', { params: { year, month } })
  },
  // 다른 월 예산을 이 달로 복사(전월 복사 등)
  copyBudget({ fromYear, fromMonth, toYear, toMonth }) {
    return http.post('/account/budgets/copy', null, { params: { fromYear, fromMonth, toYear, toMonth } })
  },
  budgetStatus({ year, month }) {
    return http.get('/account/budgets/status', { params: { year, month } })
  },
  budgetPeriod({ unit, year, month }) {
    return http.get('/account/budgets/period', { params: { unit, year, month } })
  },
  expectedIncome({ year, month }) {
    return http.get('/account/budgets/income', { params: { year, month } })
  },
  setExpectedIncome({ year, month, expectedIncome }) {
    return http.put('/account/budgets/income', { expectedIncome }, { params: { year, month } })
  },
  createBudget(payload, { year, month } = {}) {
    return http.post('/account/budgets', payload, { params: { year, month } })
  },
  updateBudget(id, payload) {
    return http.put(`/account/budgets/${id}`, payload)
  },
  removeBudget(id) {
    return http.delete(`/account/budgets/${id}`)
  },
  // 1회성 예산
  onetimeBudgets() {
    return http.get('/account/budgets/onetime')
  },
  createOnetimeBudget(payload) {
    return http.post('/account/budgets/onetime', payload)
  },
  updateOnetimeBudget(id, payload) {
    return http.put(`/account/budgets/onetime/${id}`, payload)
  },
  removeOnetimeBudget(id) {
    return http.delete(`/account/budgets/onetime/${id}`)
  },
  createWallet(payload) {
    return http.post('/account/wallets', payload)
  },
  updateWallet(id, payload) {
    return http.put(`/account/wallets/${id}`, payload)
  },
  removeWallet(id) {
    return http.delete(`/account/wallets/${id}`)
  },
  reorderWallets(type, ids) {
    return http.put('/account/wallets/reorder', { type, ids })
  },
  walletEntries(id) {
    return http.get(`/account/wallets/${id}/entries`)
  },

  // 투자 포트폴리오 (C) — 종목/매매
  investHoldings(walletId) {
    return http.get('/account/invest/holdings', { params: { walletId } })
  },
  createHolding(payload) {
    return http.post('/account/invest/holdings', payload)
  },
  updateHolding(id, payload) {
    return http.put(`/account/invest/holdings/${id}`, payload)
  },
  removeHolding(id) {
    return http.delete(`/account/invest/holdings/${id}`)
  },
  refreshPrices(walletId) {
    return http.post('/account/invest/holdings/refresh-prices', null, { params: { walletId } })
  },
  refreshAllPrices() {
    return http.post('/account/invest/refresh-prices')
  },
  holdingTrades(holdingId) {
    return http.get(`/account/invest/holdings/${holdingId}/trades`)
  },
  addTrade(holdingId, payload) {
    return http.post(`/account/invest/holdings/${holdingId}/trades`, payload)
  },
  updateTrade(id, payload) {
    return http.put(`/account/invest/trades/${id}`, payload)
  },
  removeTrade(id) {
    return http.delete(`/account/invest/trades/${id}`)
  },

  // 분류(카테고리) — 사용자별
  categories() {
    return http.get('/account/categories')
  },
  createCategory(payload) {
    return http.post('/account/categories', payload)
  },
  updateCategory(id, payload) {
    return http.put(`/account/categories/${id}`, payload)
  },
  removeCategory(id) {
    return http.delete(`/account/categories/${id}`)
  },
  reorderCategories(type, ids) {
    return http.put('/account/categories/reorder', { type, ids })
  },
  importCategories() {
    return http.post('/account/categories/import')
  },

  // 사용자별 가계부 태그
  tags() {
    return http.get('/account/tags')
  },
  createTag(payload) {
    return http.post('/account/tags', payload)
  },
  updateTag(id, payload) {
    return http.put(`/account/tags/${id}`, payload)
  },
  removeTag(id) {
    return http.delete(`/account/tags/${id}`)
  },
  reorderTags(ids) {
    return http.put('/account/tags/reorder', { ids })
  },

  // 카드 결제 알림 자동인식 (미확인 내역)
  pendingCount() {
    return http.get('/account/entries/pending/count')
  },
  confirmEntry(id, payload) {
    return http.post(`/account/entries/${id}/confirm`, payload || {})
  },

  // 데이터 복구(가져오기) — 전체 데이터 덮어쓰기
  restore(payload) {
    return http.post('/account/restore', payload)
  },

  // 가계부 데이터 전체 삭제 (내역·계좌·분류·태그·예산·고정지출·투자 전부)
  deleteAllData() {
    return http.delete('/account/all')
  },

  // 포인트 상점 — 현황 조회 / 아이템 구매
  shopStatus() {
    return http.get('/account/shop/status')
  },
  buyShopItem(item) {
    return http.post('/account/shop/buy', { item })
  },

  // 영수증 OCR (백엔드가 Google Vision 호출 → 전체 텍스트 반환) — AI 폴백용
  // suppressNetError: runOcr 이 자체 formError 로 안내하므로 전역 배너 억제
  ocrReceipt(blob) {
    const fd = new FormData()
    fd.append('image', blob, 'receipt.jpg')
    return http.post('/account/ocr/receipt', fd, {
      headers: { 'Content-Type': 'multipart/form-data' },
      timeout: 30000,
      suppressNetError: true,
    })
  },
  // 영수증 AI 구조화 (Claude Vision) — 금액·상호·날짜·분류·계좌를 한 번에. 사용자 후보 목록을 함께 전달
  // 비전 처리가 느릴 수 있어 타임아웃 상향, 실패 시 OCR 폴백이 있으므로 전역 배너 억제
  parseReceiptAi(blob, { categoryHints = [], walletHints = [] } = {}) {
    const fd = new FormData()
    fd.append('image', blob, 'receipt.jpg')
    // 멀티파트 파트 수 제한(Tomcat 기본 10) 회피: 후보를 각각 한 파트에 줄바꿈으로 합쳐 전송
    if (categoryHints.length) fd.append('categoryHints', categoryHints.join('\n'))
    if (walletHints.length) fd.append('walletHints', walletHints.join('\n'))
    return http.post('/account/ocr/receipt-ai', fd, {
      headers: { 'Content-Type': 'multipart/form-data' },
      timeout: 60000,
      suppressNetError: true,
    })
  },
}

// ===== 둘러보기(데모) 모드 =====
// demo.on 이면 읽기는 더미 데이터, 쓰기는 차단(안내 메시지)으로 응답한다.
const DEMO_READS = {
  list: demoApi.list,
  summary: demoApi.summary,
  wallets: demoApi.wallets,
  netWorth: demoApi.netWorth,
  categories: demoApi.categories,
  recurrings: demoApi.recurrings,
  quickEntries: demoApi.quickEntries,
  pendingCount: demoApi.pendingCount,
  tags: demoApi.tags,
  walletEntries: demoApi.walletEntries,
}
const DEMO_WRITES = new Set([
  'create', 'update', 'remove', 'parseText', 'createQuickEntry', 'removeQuickEntry', 'repayment',
  'createRecurring', 'updateRecurring', 'removeRecurring', 'runRecurrings',
  'createWallet', 'updateWallet', 'removeWallet', 'reorderWallets',
  'createCategory', 'updateCategory', 'removeCategory', 'reorderCategories', 'importCategories',
  'createTag', 'updateTag', 'removeTag', 'reorderTags', 'confirmEntry', 'ocrReceipt', 'parseReceiptAi', 'aiComment', 'restore', 'deleteAllData', 'buyShopItem',
  'createBudget', 'updateBudget', 'removeBudget', 'setExpectedIncome',
  'createHolding', 'updateHolding', 'removeHolding', 'addTrade', 'updateTrade', 'removeTrade',
  'refreshPrices', 'refreshAllPrices',
])

export const accountApi = new Proxy(realApi, {
  get(target, prop) {
    if (demo.on) {
      if (DEMO_READS[prop]) return DEMO_READS[prop]
      if (DEMO_WRITES.has(prop)) return () => demoApi.block()
    }
    return target[prop]
  },
})
