import { defineStore } from 'pinia'
import { api } from '../lib/api'

let refreshPromise = null

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    status: 'idle',
    hydrated: false,
  }),
  actions: {
    async refresh() {
      if (refreshPromise) return refreshPromise
      this.status = 'loading'
      refreshPromise = (async () => {
        try {
          const data = await api.me()
          this.user = data.user
          return this.user
        } catch (error) {
          this.user = null
          return null
        } finally {
          this.status = 'idle'
          this.hydrated = true
          refreshPromise = null
        }
      })()
      return refreshPromise
    },
    async signup(email, nickname, password) {
      const data = await api.signup({ email, nickname, password })
      this.user = data?.user || null
      this.hydrated = true
      return data
    },
    async login(email, password) {
      const data = await api.login({ email, password })
      this.user = data?.user || null
      this.hydrated = true
      return data?.user || null
    },
    async verifyEmail(token) {
      const data = await api.verifyEmail({ token })
      this.user = data?.user || null
      this.hydrated = true
      return this.user
    },
    async confirmPasswordReset(token, password) {
      const data = await api.confirmPasswordReset({ token, password })
      this.user = data?.user || null
      this.hydrated = true
      return this.user
    },
    async logout() {
      await api.logout()
      this.user = null
      this.hydrated = true
    },
  },
})
