import { defineStore } from 'pinia'
import type { User } from '~/types'

interface AuthState {
  user: User | null
  token: string | null
  refreshToken: string | null
  loggedIn: boolean
}

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    user: null,
    token: null,
    refreshToken: null,
    loggedIn: false,
  }),

  getters: {
    isLoggedIn: (state) => state.loggedIn,
    currentUser: (state) => state.user,
    userRole: (state) => state.user?.role || [],
    isAdmin: (state) =>
      state.user?.role?.some((r) =>
        ['Admin', 'Admin-Customer-Service', 'Admin-Procurement-Operations', 'Admin-Finance'].includes(r),
      ) || false,
  },

  actions: {
    setAuth(data: { access_token: string; me: User; refresh_token?: string }) {
      this.token = data.access_token
      this.user = data.me
      this.refreshToken = data.refresh_token || null
      this.loggedIn = true

      // Persist to cookies
      const tokenCookie = useCookie('auth_token', { maxAge: 300, secure: true })
      const refreshCookie = useCookie('auth_refresh_token', { maxAge: 60 * 60 * 24 * 30 })
      const userCookie = useCookie('auth_user', { maxAge: 60 * 60 * 24 * 30 })

      tokenCookie.value = data.access_token
      if (data.refresh_token) refreshCookie.value = data.refresh_token
      userCookie.value = JSON.stringify(data.me)

      // Store user details in localStorage for compatibility
      if (import.meta.client) {
        localStorage.setItem('userDetails', JSON.stringify(data.me))
      }
    },

    async fetchUser() {
      try {
        const config = useRuntimeConfig()
        const res = await $fetch<{ data: User }>('/auth/me', {
          baseURL: config.public.apiBaseUrl as string,
          method: 'POST',
          headers: { Authorization: `Bearer ${this.token}` },
        })
        this.user = res.data
      } catch {
        this.logout()
      }
    },

    logout() {
      // Try to call logout endpoint
      if (this.token) {
        const config = useRuntimeConfig()
        $fetch('/auth/logout', {
          baseURL: config.public.apiBaseUrl as string,
          method: 'POST',
          headers: { Authorization: `Bearer ${this.token}` },
        }).catch(() => {})
      }

      this.token = null
      this.refreshToken = null
      this.user = null
      this.loggedIn = false

      // Clear cookies
      const tokenCookie = useCookie('auth_token')
      const refreshCookie = useCookie('auth_refresh_token')
      const userCookie = useCookie('auth_user')
      tokenCookie.value = null
      refreshCookie.value = null
      userCookie.value = null

      if (import.meta.client) {
        localStorage.removeItem('auth._token.local')
        localStorage.removeItem('userDetails')
      }
    },

    restoreFromCookies() {
      const tokenCookie = useCookie('auth_token')
      const refreshCookie = useCookie('auth_refresh_token')
      const userCookie = useCookie('auth_user')

      if (tokenCookie.value) {
        this.token = tokenCookie.value
        this.loggedIn = true

        if (refreshCookie.value) {
          this.refreshToken = refreshCookie.value
        }

        if (userCookie.value) {
          try {
            this.user = typeof userCookie.value === 'string'
              ? JSON.parse(userCookie.value)
              : userCookie.value
          } catch {
            // Invalid user cookie
          }
        }
      }
    },

    async refreshTokens() {
      if (!this.refreshToken) return

      try {
        const config = useRuntimeConfig()
        const res = await $fetch<{ access_token: string }>('/auth/refresh', {
          baseURL: config.public.apiBaseUrl as string,
          method: 'POST',
          body: { refresh_token: this.refreshToken },
        })

        this.token = res.access_token
        const tokenCookie = useCookie('auth_token', { maxAge: 300, secure: true })
        tokenCookie.value = res.access_token
      } catch {
        this.logout()
      }
    },
  },
})
