import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { AccountAuth } from '@/types/account'
import type { MemberProfile } from '@/types/account'
import { useAuthStore } from '@/stores/auth'
import { useSecurityStore } from '@/stores/security'

export interface Device {
  id: string
  os: string
  browser: string
  ip: string
  lastLoginAt: string
  isCurrent: boolean
}

export interface AccountInfo {
  uid: string
  email: string
  registeredAt: string
  /** 与 `MemberProfile.avatar`、跟单客户头像同源 */
  avatar: string | null
  securityScore: 'low' | 'medium' | 'high'
  twoFactorEnabled: boolean
  googleAuthEnabled: boolean
  fundPasswordSet: boolean
  emailVerified: boolean
}

export const useAccountStore = defineStore('account', () => {
  const info = ref<AccountInfo | null>(null)
  const devices = ref<Device[]>([])
  const inviteCode = ref('')
  const loading = ref(false)
  const error = ref('')

  async function fetchInfo() {
    loading.value = true
    error.value = ''
    try {
      const authStore = useAuthStore()
      const securityStore = useSecurityStore()
      await authStore.fetchMyInfo()
      await securityStore.fetchSecuritySetting()
      info.value = mergeAccountDisplay(authStore.memberProfile, securityStore.auth)
    } catch (e) {
      error.value = e instanceof Error ? e.message : '获取账户信息失败'
    } finally {
      loading.value = false
    }
  }

  async function fetchDevices() {
    loading.value = true
    try {
      await mockDelay()
      devices.value = getMockDevices()
    } finally {
      loading.value = false
    }
  }

  async function fetchInviteInfo() {
    loading.value = true
    try {
      const authStore = useAuthStore()
      if (!authStore.memberProfile) {
        await authStore.fetchMyInfo()
      }
      inviteCode.value = authStore.memberProfile?.inviteCode ?? ''
    } finally {
      loading.value = false
    }
  }

  async function revokeDevice(deviceId: string) {
    devices.value = devices.value.filter(d => d.id !== deviceId)
  }

  async function revokeAllOtherDevices() {
    devices.value = devices.value.filter(d => d.isCurrent)
  }

  return {
    info,
    devices,
    inviteCode,
    loading,
    error,
    fetchInfo,
    fetchDevices,
    fetchInviteInfo,
    revokeDevice,
    revokeAllOtherDevices,
  }
})

function mergeAccountDisplay(profile: MemberProfile | null, auth: AccountAuth | null): AccountInfo | null {
  if (!profile && !auth) {
    return null
  }

  const uid = profile?.uid ?? String(auth?.id ?? '')
  const email = profile?.email ?? auth?.email ?? ''
  const registeredAt = profile?.registeredAt ?? ''

  const googleAuthEnabled = Number(auth?.googleStatus) === 1
  const fundPasswordSet = Number(auth?.fundsVerified) === 1
  const emailVerified = Number(auth?.emailVerified) === 1

  let securityScore: AccountInfo['securityScore'] = 'low'
  {
    let score = 0
    if (emailVerified) {
      score++
    }
    if (googleAuthEnabled) {
      score++
    }
    if (fundPasswordSet) {
      score++
    }
    if (score >= 3) {
      securityScore = 'high'
    } else if (score >= 2) {
      securityScore = 'medium'
    }
  }

  return {
    uid,
    email,
    registeredAt,
    avatar: profile?.avatar ?? null,
    securityScore,
    twoFactorEnabled: googleAuthEnabled,
    googleAuthEnabled,
    fundPasswordSet,
    emailVerified,
  }
}

function mockDelay(ms = 400) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

function getMockDevices(): Device[] {
  return [
    { id: '1', os: 'macOS 14', browser: 'Chrome 122', ip: '192.168.1.1', lastLoginAt: '2026-03-18 10:00', isCurrent: true },
    { id: '2', os: 'Windows 11', browser: 'Edge 121', ip: '10.0.0.5', lastLoginAt: '2026-03-15 18:30', isCurrent: false },
  ]
}
