import { defineStore } from 'pinia'
import { userService } from '../../services/userService.js'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    status: 'idle',
    error: null,
  }),
  getters: {
    isLoggedIn: (state) => !!state.user,
    creditsBalance: (state) => state.user?.creditsBalance ?? 0,
    freeUsed: (state) => state.user?.freeUsed ?? false,
    canConvert: (state) => {
      if (!state.user) return false
      if (!state.user.freeUsed) return true
      return state.user.creditsBalance > 0
    },
  },
  actions: {
    async fetchMe() {
      const user = await userService.getMe()
      this.user = user
    },
    async login(email, password) {
      this.status = 'loading'
      this.error = null
      try {
        this.user = await userService.login(email, password)
        this.status = 'idle'
      } catch (e) {
        this.error = e.message
        this.status = 'error'
      }
    },
    async logout() {
      await userService.logout()
      this.user = null
    },
    async register(email, password, name) {
      this.status = 'loading'
      this.error = null
      try {
        this.user = await userService.register(email, password, name)
        this.status = 'idle'
      } catch (e) {
        this.error = e.message
        this.status = 'error'
      }
    },
    refreshBalance(newBalance) {
      if (this.user) this.user.creditsBalance = newBalance
    },
  },
})
