import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

function parseJson(value: string | null): string[] {
  if (!value) return []
  try {
    const parsed = JSON.parse(value)
    return Array.isArray(parsed) ? parsed : []
  } catch {
    return []
  }
}

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('mci-token') || '')
  const tenantCode = ref(localStorage.getItem('mci-tenant-code') || '')
  const username = ref(localStorage.getItem('mci-username') || '')
  const roleCodes = ref<string[]>(parseJson(localStorage.getItem('mci-role-codes')))

  const isLoggedIn = computed(() => !!token.value)

  function setAuth(t: string, tc: string, user: string, roles: string[]) {
    token.value = t
    tenantCode.value = tc
    username.value = user
    roleCodes.value = roles
    localStorage.setItem('mci-token', t)
    localStorage.setItem('mci-tenant-code', tc)
    localStorage.setItem('mci-username', user)
    localStorage.setItem('mci-role-codes', JSON.stringify(roles))
  }

  function setTenant(code: string) {
    tenantCode.value = code
    localStorage.setItem('mci-tenant-code', code)
  }

  function clearAuth() {
    token.value = ''
    tenantCode.value = ''
    username.value = ''
    roleCodes.value = []
    localStorage.removeItem('mci-token')
    localStorage.removeItem('mci-tenant-code')
    localStorage.removeItem('mci-username')
    localStorage.removeItem('mci-role-codes')
  }

  return { token, tenantCode, username, roleCodes, isLoggedIn, setAuth, setTenant, clearAuth }
})
