import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User, License } from '@/types'

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null)
  const license = ref<License | null>(null)
  const accessToken = ref<string | null>(null)
  const refreshToken = ref<string | null>(null)

  const isAuthenticated = computed(() => !!accessToken.value)
  const isSuperAdmin = computed(() => user.value?.is_super_admin ?? false)
  const hasLicense = computed(() => !!license.value)
  const isLicenseActive = computed(() => license.value?.status === 'active')

  function setAuth(data: { access_token: string; refresh_token: string; user: User }) {
    accessToken.value = data.access_token
    refreshToken.value = data.refresh_token
    user.value = data.user
  }

  function setLicense(data: License) {
    license.value = data
  }

  function logout() {
    user.value = null
    license.value = null
    accessToken.value = null
    refreshToken.value = null
  }

  function hasModule(moduleSlug: string): boolean {
    return license.value?.modules_enabled?.includes(moduleSlug) ?? false
  }

  return {
    user,
    license,
    accessToken,
    refreshToken,
    isAuthenticated,
    isSuperAdmin,
    hasLicense,
    isLicenseActive,
    setAuth,
    setLicense,
    logout,
    hasModule,
  }
}, {
  persist: {
    pick: ['accessToken', 'refreshToken', 'user', 'license'],
  },
})
