import { ref } from 'vue'
import { defineStore } from 'pinia'
import { getWelcomeMessage, type WelcomeMessageData } from '@/api/welcome'

function formatRequestDate(date = new Date()) {
  const pad = (n: number) => String(n).padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}

/** 可通过 updateState 批量更新的字段 */
export interface AppStateUpdates {
  terminal?: string
  accessToken?: string
  familyId?: string
  deviceType?: string
  deviceCategory?: string
  deviceName?: string
  deviceId?: string
  deviceGuid?: string
  userId?: string
}

export const useAppStore = defineStore('app', () => {
  /** 应用展示名，可在启动时由接口或配置覆盖 */
  const appName = ref('Roki H5')
  const terminal = ref('android')
  const deviceName = ref('燃气热水器·HT808-16')
  const familyId = ref('')
  const deviceId = ref('HT80888a68d0fb812')
  const deviceGuid = ref('HT80888a68d0fb812')
  const deviceType = ref('HT808')
  const deviceCategory = ref('RRSQ')
  const userId = ref('3243300064')

  /** 开发联调用 token，生产环境由 App 注入覆盖 */
  const accessToken = ref(
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE4MDI5Mjg0ODAsInVzZXJJZCI6MzI0MzMwMDA2NCwianRpIjoiMDI3ZjhiMGMtYmU5MS00NzA2LWI3ZDUtOGI5OTJlMjA0MzQ2IiwiY2xpZW50X2lkIjoicm9raV9jbGllbnQifQ.aW0hKvcv-k_4PocYNVWiml7IB15jZIcn24eXZFZCSz4',
  )

  /** `/rest/ops/ai/welcome` 的 data：prefix / speech */
  const welcomeCopy = ref<WelcomeMessageData>({})

  function setAppName(name: string) {
    appName.value = name
  }

  function setAccessToken(token: string) {
    accessToken.value = token
  }

  function resetWelcomeCopy() {
    welcomeCopy.value = {}
  }

  async function loadWelcomeMessage(params: Record<string, unknown> = {}) {
    try {
      const res = await getWelcomeMessage({
        date: formatRequestDate(),
        ...params,
      })
      welcomeCopy.value = res?.data ?? {}
    } catch (e) {
      welcomeCopy.value = {}
      if (import.meta.env.DEV) {
        console.warn('[App] loadWelcomeMessage failed', e)
      }
    }
  }

  function updateState(updates: AppStateUpdates) {
    const stateRefs = {
      terminal,
      accessToken,
      familyId,
      deviceType,
      deviceCategory,
      deviceName,
      deviceId,
      deviceGuid,
      userId,
    } as const

    Object.entries(updates).forEach(([key, value]) => {
      if (key in stateRefs) {
        stateRefs[key as keyof typeof stateRefs].value = value as never
      } else if (import.meta.env.DEV) {
        console.warn(`[App] updateState: unknown key "${key}"`)
      }
    })
  }

  return {
    appName,
    terminal,
    deviceName,
    familyId,
    deviceId,
    deviceGuid,
    deviceType,
    deviceCategory,
    userId,
    accessToken,
    welcomeCopy,
    setAppName,
    setAccessToken,
    resetWelcomeCopy,
    loadWelcomeMessage,
    updateState,
  }
})
