import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { GoogleAuthenticatorSecret } from '@/types/account'
import { get, postForm } from '@/utils/request'

const COUNTDOWN_SEC = 60

export const useGoogleAuthStore = defineStore('googleAuth', () => {
  const secret = ref('')
  const otpauthUrl = ref('')
  const isSecretLoading = ref(false)
  const sendingCode = ref(false)
  const submitting = ref(false)
  const codeCountdown = ref(0)
  const error = ref<string | null>(null)

  let countdownTimer: ReturnType<typeof setInterval> | null = null

  function stopCountdown() {
    if (countdownTimer) {
      clearInterval(countdownTimer)
      countdownTimer = null
    }
    codeCountdown.value = 0
  }

  function startCountdown() {
    stopCountdown()
    codeCountdown.value = COUNTDOWN_SEC
    countdownTimer = setInterval(() => {
      codeCountdown.value--
      if (codeCountdown.value <= 0) {
        stopCountdown()
      }
    }, 1000)
  }

  async function fetchSecret() {
    isSecretLoading.value = true
    error.value = null
    try {
      const data = await get<GoogleAuthenticatorSecret>('/uc/google/sendgoogle')
      otpauthUrl.value = data.link ?? ''
      secret.value = data.secret ?? ''
    } catch (e) {
      error.value = e instanceof Error ? e.message : '获取密钥失败'
      throw e
    } finally {
      isSecretLoading.value = false
    }
  }

  async function sendEmailCode() {
    sendingCode.value = true
    error.value = null
    try {
      await postForm('/uc/googleAuth/email/code', {})
      startCountdown()
    } catch (e) {
      error.value = e instanceof Error ? e.message : '验证码发送失败'
      throw e
    } finally {
      sendingCode.value = false
    }
  }

  async function bindGoogleAuth(codes: string, emailVcode: string, secretVal: string) {
    submitting.value = true
    error.value = null
    try {
      await postForm('/uc/google/googleAuthWithSms', {
        codes,
        vtype: '2',
        vcode: emailVcode,
        secret: secretVal,
      })
    } catch (e) {
      error.value = e instanceof Error ? e.message : '绑定失败'
      throw e
    } finally {
      submitting.value = false
    }
  }

  function resetLocal() {
    secret.value = ''
    otpauthUrl.value = ''
    error.value = null
    stopCountdown()
  }

  return {
    secret,
    otpauthUrl,
    isSecretLoading,
    sendingCode,
    submitting,
    codeCountdown,
    error,
    fetchSecret,
    sendEmailCode,
    bindGoogleAuth,
    resetLocal,
    stopCountdown,
  }
})
