import { checkImpersonationStatus, fetchProfileApi, loginApi, logoutApi, registerApi, stopImpersonationApi, updatePasswordApi } from '@/api/authApi'
import { showToast } from '@/composables/useStoreHelpers'
import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    loading: false,
    error: null,
    isAuthenticated: null,
    // ✅ NEW: Impersonation state
    impersonator: null,
    isImpersonating: false,
    impersonationLoading: false
  }),

  actions: {
    async login(credentials) {
      this.loading = true
      this.error = null
      try {
        await loginApi(credentials)
        await this.fetchProfile()
        // showToast('success', '', 'Login successful')
        return true
      } catch (error) {
        this.error = error.response?.data?.message || error.message
        showToast('error', '', this.error)
        // Add a small delay to ensure toast is visible
        await new Promise(resolve => setTimeout(resolve, 500))
        return false
      } finally {
        this.loading = false
      }
    },

    async register(payload) {
      this.loading = true
      this.error = null

      try {
        await registerApi(payload)
        await this.fetchProfile()
        showToast('success', '', 'Registration successful')
        return true
      } catch (error) {
        this.error = error.response?.data?.message || error.message
        showToast('error', '', this.error)
        return false
      } finally {
        this.loading = false
      }
    },

    async fetchProfile() {
      try {
        const { data } = await fetchProfileApi()
        this.user = data
        console.log('Logged in user detail:', this.user)
        this.isAuthenticated = true
      } catch (err) {
        this.user = null
        this.isAuthenticated = false
      }
    },

    async logout() {
      try {
        await logoutApi()
      } catch (err) {
        // ignore logout API errors (e.g., 401)
      } finally {
        this.forceLogout()
      }
    },

    forceLogout() {
      this.user = null
      this.isAuthenticated = false
      this.loading = false
      this.error = null
      
      // Clear all localStorage to prevent cached data from showing for different users
      localStorage.clear()
      
      console.log('User logged out - all cache cleared')
    },
        
    async updatePassword(payload) {
      this.loading = true
      this.error = null
      
      try {
        const res = await updatePasswordApi(payload)
        showToast('success', '', 'Password updated successfully')
        return res.data
      } catch (error) {
        this.error = error.response?.data?.message || error.message || 'Failed to update password'
        showToast('error', '', this.error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // ✅ NEW: Check if super admin is impersonating
    async checkImpersonationStatus() {
      this.impersonationLoading = true
      try {
        const response = await checkImpersonationStatus()
        const impersonator = response.data?.data?.impersonator
        
        if (impersonator) {
          this.impersonator = impersonator
          this.isImpersonating = true
        } else {
          this.impersonator = null
          this.isImpersonating = false
        }
        
        return {
          isImpersonating: this.isImpersonating,
          impersonator: this.impersonator
        }
      } catch (error) {
        console.error('Error checking impersonation status:', error)
        this.impersonator = null
        this.isImpersonating = false
        return {
          isImpersonating: false,
          impersonator: null
        }
      } finally {
        this.impersonationLoading = false
      }
    },

    // ✅ NEW: Stop impersonation and return to super admin
    async stopImpersonation() {
      this.impersonationLoading = true
      this.impersonator = null
      this.isImpersonating = false
      try {
       const response =  await stopImpersonationApi()
        if (response.status && response.data?.data?.redirect_url) {
          return {
            success: true,
            url: response.data.data.redirect_url,
          }
        } else {
          throw new Error('No URL in response')
        }
      } catch (error) {
        this.error = error.response?.data?.message || error.message
        showToast('error', 'Error', this.error || 'Failed to stop impersonation')
        return false
      } finally {
        this.impersonationLoading = false
      }
    }
  },

  getters: {
    // ✅ NEW: Check if currently impersonating
    canReturnToDashboard: (state) => state.isImpersonating && state.impersonator
  }
})
