import { defineStore } from 'pinia'
import { authAPI } from '@/services/auth'
import { ElMessage } from 'element-plus'
import Cookies from 'js-cookie'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    isAuthenticated: false,
    token: null,
    refreshToken: null,
    loading: false
  }),
  
  getters: {
    isAdmin: (state) => state.user?.is_admin || false,
    userName: (state) => state.user?.display_name || '',
    userEmail: (state) => state.user?.email || '',
    department: (state) => state.user?.department || ''
  },
  
  actions: {
    /**
     * 使用者登入
     * @param {Object} credentials - 登入憑證
     */
    async login(credentials) {
      try {
        this.loading = true
        console.log('🔑 [Auth] 開始登入流程', credentials.username)
        
        const response = await authAPI.login(credentials)
        console.log('🔑 [Auth] 登入 API 回應', response)
        
        if (response.success) {
          this.user = response.data.user
          this.token = response.data.access_token  // 改為使用 access_token
          this.refreshToken = response.data.refresh_token  // 儲存 refresh_token
          this.isAuthenticated = true
          
          console.log('🔑 [Auth] 設定認證狀態', {
            user: this.user,
            token: this.token ? `${this.token.substring(0, 20)}...` : null,
            isAuthenticated: this.isAuthenticated
          })
          
          // 儲存認證資訊到 localStorage
          localStorage.setItem('auth_user', JSON.stringify(response.data.user))
          localStorage.setItem('auth_token', this.token)
          localStorage.setItem('auth_refresh_token', this.refreshToken)
          localStorage.setItem('auth_authenticated', 'true')
          
          // JWT 不需要 cookie，移除 cookie 設定
          
          console.log('🔑 [Auth] 登入成功，JWT tokens 已儲存')
          ElMessage.success(response.message || '登入成功')
          return response.data
        } else {
          throw new Error(response.message || '登入失敗')
        }
      } catch (error) {
        console.error('❌ [Auth] 登入錯誤:', error)
        this.clearAuth()
        throw error
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 使用者登出
     */
    async logout() {
      try {
        console.log('🚪 [Auth] 開始登出流程')
        await authAPI.logout()
        console.log('🚪 [Auth] 登出 API 完成')
      } catch (error) {
        console.error('❌ [Auth] 登出錯誤:', error)
      } finally {
        console.log('🚪 [Auth] 清除認證資料')
        this.clearAuth()
        ElMessage.success('已安全登出')
      }
    },
    
    /**
     * 檢查認證狀態
     */
    async checkAuth() {
      try {
        // 先檢查 localStorage 中的認證資訊
        const authUser = localStorage.getItem('auth_user')
        const authToken = localStorage.getItem('auth_token')
        const authRefreshToken = localStorage.getItem('auth_refresh_token')
        const authAuthenticated = localStorage.getItem('auth_authenticated')
        
        if (!authUser || !authToken || authAuthenticated !== 'true') {
          return false
        }
        
        // 恢復認證狀態
        this.user = JSON.parse(authUser)
        this.token = authToken
        this.refreshToken = authRefreshToken
        this.isAuthenticated = true
        
        console.log('🔑 [Auth] 從 localStorage 恢復認證狀態', {
          user: this.user,
          hasToken: !!this.token,
          hasRefreshToken: !!this.refreshToken
        })
        
        return true
        
      } catch (error) {
        console.error('❌ [Auth] 認證檢查失敗:', error)
        this.clearAuth()
        return false
      }
    },
    
    /**
     * 刷新用戶資訊
     */
    async refreshUser() {
      try {
        const response = await authAPI.getCurrentUser()
        
        if (response.success && response.data.user) {
          this.user = response.data.user
        }
      } catch (error) {
        console.error('刷新用戶資訊失敗:', error)
        this.clearAuth()
      }
    },
    
    /**
     * 清除認證資訊
     */
    clearAuth() {
      console.log('🧡 [Auth] 清除認證資料前', {
        user: this.user,
        token: this.token,
        refreshToken: this.refreshToken,
        isAuthenticated: this.isAuthenticated
      })
      
      this.user = null
      this.token = null
      this.refreshToken = null
      this.isAuthenticated = false
      this.loading = false
      
      // 清除所有認證相關的存儲
      localStorage.removeItem('auth_user')
      localStorage.removeItem('auth_token')
      localStorage.removeItem('auth_refresh_token')
      localStorage.removeItem('auth_authenticated')
      
      console.log('🧡 [Auth] JWT 認證資料已清除')
    },
    
    /**
     * 更新用戶資訊
     * @param {Object} userData - 用戶資料
     */
    updateUser(userData) {
      if (this.user) {
        this.user = { ...this.user, ...userData }
      }
    }
  },
  
  // 持久化設定（可選）
  persist: {
    key: 'auth_store',
    storage: localStorage,
    paths: ['user', 'isAuthenticated'] // 只持久化這些欄位
  }
})