// 둘러보기(데모) 모드 — 실제 화면 컴포넌트를 그대로 쓰되 API 만 더미로 응답한다.
// demo.on 이 true 면 accountApi 의 읽기는 아래 더미를, 쓰기는 block()(안내 메시지)으로 응답.
import { reactive } from 'vue'

export const demo = reactive({ on: false })

export function enterDemo() {
  demo.on = true
}
export function exitDemo() {
  demo.on = false
}

// ===== 더미 데이터 (백엔드 응답 DTO 형태와 동일) =====
const WALLETS = [
  { id: 1, type: 'BANK', name: '신한 주거래', issuer: '신한', accountNumber: null, openingBalance: 0, balance: 2540000, manualValuation: false },
  { id: 2, type: 'BANK', name: '주택청약', issuer: '국민', accountNumber: null, openingBalance: 0, balance: 5000000, manualValuation: false },
  { id: 3, type: 'CASH', name: '현금', openingBalance: 0, balance: 120000, manualValuation: false },
  { id: 4, type: 'CARD', name: '삼성카드', issuer: '삼성', cardType: 'CREDIT', openingBalance: 0, balance: -340000, manualValuation: false },
  {
    id: 5, type: 'INVEST', name: '연금저축', manualValuation: true,
    investedAmount: 7000000, currentValue: 8200000, balance: 8200000,
    valuationGain: 1200000, deposit: 0, stockValue: 8200000,
  },
]

const CATEGORIES = [
  // 지출 대분류/소분류
  { id: 10, type: 'EXPENSE', name: '식비', parentId: null },
  { id: 11, type: 'EXPENSE', name: '점심', parentId: 10 },
  { id: 12, type: 'EXPENSE', name: '저녁', parentId: 10 },
  { id: 13, type: 'EXPENSE', name: '카페/간식', parentId: 10 },
  { id: 20, type: 'EXPENSE', name: '교통', parentId: null },
  { id: 21, type: 'EXPENSE', name: '대중교통', parentId: 20 },
  { id: 22, type: 'EXPENSE', name: '택시', parentId: 20 },
  { id: 30, type: 'EXPENSE', name: '주거/통신', parentId: null },
  { id: 31, type: 'EXPENSE', name: '월세', parentId: 30 },
  { id: 32, type: 'EXPENSE', name: '통신비', parentId: 30 },
  { id: 40, type: 'EXPENSE', name: '문화/여가', parentId: null },
  { id: 41, type: 'EXPENSE', name: 'OTT/구독', parentId: 40 },
  { id: 50, type: 'EXPENSE', name: '쇼핑', parentId: null },
  // 수입
  { id: 60, type: 'INCOME', name: '급여', parentId: null },
  { id: 61, type: 'INCOME', name: '용돈', parentId: null },
]

// 이번 달(현 시점) 기준 샘플 내역
function ymd(day) {
  const now = new Date()
  const m = String(now.getMonth() + 1).padStart(2, '0')
  return `${now.getFullYear()}-${m}-${String(day).padStart(2, '0')}`
}
function E(id, day, type, category, amount, memo, walletId, walletName, opt = {}) {
  return {
    id, entryDate: ymd(day), type, category, amount, memo,
    walletId, walletName, toWalletId: null, toWalletName: null,
    installmentMonths: null, pending: !!opt.pending, tags: opt.tags || [],
  }
}
const ENTRIES = [
  E(101, 27, 'EXPENSE', '점심', 9000, '김밥천국', 4, '삼성카드'),
  E(102, 27, 'EXPENSE', '카페/간식', 5300, '스타벅스', 4, '삼성카드'),
  E(103, 27, 'EXPENSE', '대중교통', 2800, '지하철', 3, '현금'),
  E(104, 27, 'EXPENSE', '쇼핑', 25200, '다이소', 4, '삼성카드', { pending: true }),
  E(105, 25, 'INCOME', '급여', 4600000, '6월 급여', 1, '신한 주거래'),
  E(106, 25, 'EXPENSE', '통신비', 45300, '휴대폰 요금', 1, '신한 주거래'),
  E(107, 23, 'EXPENSE', 'OTT/구독', 17000, '넷플릭스', 4, '삼성카드', { tags: ['구독'] }),
  E(108, 23, 'EXPENSE', '저녁', 23000, '배달', 4, '삼성카드'),
  E(109, 20, 'EXPENSE', '쇼핑', 285000, '마트 장보기', 4, '삼성카드'),
  E(110, 18, 'EXPENSE', '저녁', 62000, '친구 외식', 4, '삼성카드', { tags: ['데이트'] }),
  E(111, 15, 'EXPENSE', '택시', 28000, '심야 택시', 4, '삼성카드'),
  E(112, 12, 'EXPENSE', '쇼핑', 320000, '의류 구매', 4, '삼성카드'),
  E(113, 8, 'EXPENSE', '대중교통', 55000, '교통카드 충전', 3, '현금'),
  E(114, 5, 'EXPENSE', '카페/간식', 18500, '베이커리', 4, '삼성카드'),
  E(115, 1, 'EXPENSE', '월세', 600000, '6월 월세', 1, '신한 주거래'),
]

const RECURRINGS = [
  { id: 201, title: '월세', type: 'EXPENSE', amount: 600000, category: '월세', memo: null, walletId: 1, walletName: '신한 주거래', toWalletId: null, toWalletName: null, frequency: 'MONTHLY', dayOfMonth: 1, dayOfWeek: null, monthOfYear: null, startDate: ymd(1), endDate: null, lastRunDate: null, nextDate: ymd(1), active: true },
  { id: 202, title: '통신비', type: 'EXPENSE', amount: 45300, category: '통신비', memo: null, walletId: 1, walletName: '신한 주거래', toWalletId: null, toWalletName: null, frequency: 'MONTHLY', dayOfMonth: 15, dayOfWeek: null, monthOfYear: null, startDate: ymd(15), endDate: null, lastRunDate: null, nextDate: ymd(15), active: true },
  { id: 203, title: '넷플릭스', type: 'EXPENSE', amount: 17000, category: 'OTT/구독', memo: null, walletId: 4, walletName: '삼성카드', toWalletId: null, toWalletName: null, frequency: 'MONTHLY', dayOfMonth: 23, dayOfWeek: null, monthOfYear: null, startDate: ymd(23), endDate: null, lastRunDate: null, nextDate: ymd(23), active: true },
  { id: 204, title: '급여', type: 'INCOME', amount: 4600000, category: '급여', memo: null, walletId: 1, walletName: '신한 주거래', toWalletId: null, toWalletName: null, frequency: 'MONTHLY', dayOfMonth: 25, dayOfWeek: null, monthOfYear: null, startDate: ymd(25), endDate: null, lastRunDate: null, nextDate: ymd(25), active: true },
]

const QUICK = [
  { id: 301, label: '점심', type: 'EXPENSE', category: '점심', amount: 9000, memo: '점심', walletId: 4, walletName: '삼성카드' },
  { id: 302, label: '커피', type: 'EXPENSE', category: '카페/간식', amount: 5300, memo: '커피', walletId: 4, walletName: '삼성카드' },
  { id: 303, label: '대중교통', type: 'EXPENSE', category: '대중교통', amount: 2800, memo: '교통', walletId: 3, walletName: '현금' },
]

const TAGS = [
  { id: 401, name: '구독' },
  { id: 402, name: '데이트' },
  { id: 403, name: '경조사' },
]

// 해당 연·월 내역만 (월 이동 반영)
function inMonth(e, year, month) {
  if (!year || !month) return true
  return e.entryDate.startsWith(`${year}-${String(month).padStart(2, '0')}`)
}
// 검색·필터 적용
function filterEntries(p = {}) {
  let rows = ENTRIES.filter((e) => inMonth(e, p.year, p.month))
  if (p.type) rows = rows.filter((e) => e.type === p.type)
  if (p.category) rows = rows.filter((e) => e.category === p.category)
  if (p.walletId) rows = rows.filter((e) => String(e.walletId) === String(p.walletId))
  if (p.keyword) {
    const k = String(p.keyword).trim()
    rows = rows.filter((e) => (e.memo || '').includes(k) || (e.category || '').includes(k))
  }
  if (p.tagId) {
    const t = TAGS.find((x) => String(x.id) === String(p.tagId))
    if (t) rows = rows.filter((e) => (e.tags || []).includes(t.name))
  }
  return rows
}
function summaryOf(p = {}) {
  let income = 0, expense = 0
  for (const e of ENTRIES) {
    if (!inMonth(e, p.year, p.month)) continue
    if (e.type === 'INCOME') income += e.amount
    else if (e.type === 'EXPENSE') expense += e.amount
  }
  return { totalIncome: income, totalExpense: expense, balance: income - expense }
}
const NETWORTH = { totalAssets: 15860000, totalLiabilities: 340000, netWorth: 15520000 }

function ok(data) {
  // 깊은 복제로 화면에서 수정해도 원본 더미는 보존
  return Promise.resolve(JSON.parse(JSON.stringify(data)))
}
function block() {
  return Promise.reject({ response: { data: { message: '둘러보기 모드에서는 저장되지 않습니다. 로그인 후 이용해 주세요.' } } })
}

// 읽기 응답 / 쓰기 차단
export const demoApi = {
  list: (params) => ok(filterEntries(params)),
  summary: (params) => ok(summaryOf(params)),
  wallets: () => ok(WALLETS),
  netWorth: () => ok(NETWORTH),
  categories: () => ok(CATEGORIES),
  recurrings: () => ok(RECURRINGS),
  quickEntries: () => ok(QUICK),
  pendingCount: () => ok({ count: 1 }),
  tags: () => ok(TAGS),
  walletEntries: () => ok([]),
  block,
}
