import { defineStore } from 'pinia'
import { authApi } from '../api'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    accessToken: localStorage.getItem('accessToken') || '',
    refreshToken: localStorage.getItem('refreshToken') || ''
  }),
  getters: {
    isLoggedIn: state => !!state.accessToken,
    isAdmin: state => state.user?.role === 'SUPER_ADMIN',
    isHrAdminOrAbove: state => ['SUPER_ADMIN', 'HR_ADMIN'].includes(state.user?.role),
    isDeptLeaderOrAbove: state => ['SUPER_ADMIN', 'HR_ADMIN', 'DEPT_LEADER'].includes(state.user?.role),
    roleLabel: state => {
      const map = { EMPLOYEE: '员工', TEAM_LEADER: '团队主管', DEPT_LEADER: '部门负责人', HR_ADMIN: 'HR管理员', SUPER_ADMIN: '管理员' }
      return map[state.user?.role] || '员工'
    },
    roleColor: state => {
      const map = { SUPER_ADMIN: '#f56c6c', HR_ADMIN: '#e6a23c', DEPT_LEADER: '#8b5cf6', TEAM_LEADER: '#3ad4d8', EMPLOYEE: '#409eff' }
      return map[state.user?.role] || '#409eff'
    }
  },
  actions: {
    async login(username, password) {
      const result = await authApi.login({ username, password })
      this.accessToken = result.accessToken
      this.refreshToken = result.refreshToken
      this.user = result.user
      localStorage.setItem('accessToken', result.accessToken)
      localStorage.setItem('refreshToken', result.refreshToken)
    },
    async fetchUser() {
      try {
        this.user = await authApi.me()
      } catch {
        this.logout()
      }
    },
    logout() {
      this.user = null
      this.accessToken = ''
      this.refreshToken = ''
      localStorage.removeItem('accessToken')
      localStorage.removeItem('refreshToken')
    }
  }
})
