import { defineStore } from 'pinia'
import { fetchCurrentUser, switchActiveRole } from '@/modules/auth/services/auth.service'
import { fetchImpersonationStatus } from '@/modules/user/services/impersonate.service'
import type { AuthRole, AuthUser } from '@/modules/auth/types/auth.types'

interface AuthState {
  user: AuthUser | null
  activeRole: AuthRole | null
  canSwitchRole: boolean
  isImpersonating: boolean
  loading: boolean
}

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    user: null,
    activeRole: null,
    canSwitchRole: false,
    isImpersonating: false,
    loading: false,
  }),

  getters: {
    userName: (state) => state.user?.name ?? '',
    userActiveRole: (state) => state.activeRole?.name ?? '',
    userPosition: (state) => state.user?.position ?? '',
    userImageUrl: (state) => state.user?.image_url ?? null,
    userMemberNumber: (state) => state.user?.member_number ?? null,
    userMemberType: (state) => state.user?.member_type ?? null,
    userStatus: (state) => state.user?.status ?? null,
    userGender: (state) => state.user?.gender ?? null,
    userMarriageStatus: (state) => state.user?.marriage_status ?? null,
    userJoinDate: (state) => state.user?.join_date ?? null,
    userBirthDate: (state) => state.user?.birth_date ?? null,
    userBirthPlace: (state) => state.user?.birth_place ?? null,
    isAuthenticated: (state) => state.user !== null,
    isAccountPending: (state) => state.user?.status === 'pending',
    isAccountActive: (state) => state.user?.status === 'active',
    roles: (state) => state.user?.roles ?? [],
  },

  actions: {
    setSession(user: AuthUser, activeRole: AuthRole | null, canSwitchRole = false) {
      this.user = user
      this.activeRole = activeRole
      this.canSwitchRole = canSwitchRole
    },

    applySession(payload: {
      data: AuthUser
      active_role: AuthRole | null
      can_switch_role: boolean
    }) {
      this.user = payload.data
      this.activeRole = payload.active_role
      this.canSwitchRole = payload.can_switch_role
    },

    clearSession() {
      this.user = null
      this.activeRole = null
      this.canSwitchRole = false
      this.isImpersonating = false
    },

    async refreshImpersonationStatus() {
      try {
        const status = await fetchImpersonationStatus()
        this.isImpersonating = status.is_impersonating
      } catch {
        this.isImpersonating = false
      }
    },

    async fetchSession() {
      this.loading = true

      try {
        const session = await fetchCurrentUser()
        this.user = session.data
        this.activeRole = session.active_role
        this.canSwitchRole = session.can_switch_role
        await this.refreshImpersonationStatus()
      } catch {
        this.clearSession()
      } finally {
        this.loading = false
      }
    },

    async switchRole(roleId: string) {
      this.loading = true

      try {
        const res = await switchActiveRole(roleId)
        this.user = res.data
        this.activeRole = res.active_role
        this.canSwitchRole = res.can_switch_role
        return res
      } finally {
        this.loading = false
      }
    },

    setUserProfile(user: AuthUser) {
      this.user = user
    },
  },
})
