import { defineStore } from 'pinia'

import {
  fetchAdminMe,
  loginAdmin,
  type AdminRole,
  type AdminUser,
} from '@/features/admin/api/adminAuth'
import { clearAuthStorage } from '@/shared/utils/authStorage'

export const useAdminSessionStore = defineStore('adminSession', {
  state: () => ({
    token: '',
    refreshToken: '',
    adminId: Number(localStorage.getItem('admin_id') || 0),
    username: localStorage.getItem('admin_username') || '',
    nickname: '',
    supportStatus: (localStorage.getItem('admin_support_status') || 'offline') as
      | 'online'
      | 'offline'
      | 'busy',
    passwordMustChange: localStorage.getItem('admin_password_must_change') === 'true',
    roles: [] as AdminRole[],
    permissions: [] as string[],
  }),
  getters: {
    hasSessionHint: state => state.adminId > 0 || state.username !== '',
    hasPermission: state => {
      return (code: string) => state.permissions.includes(code) || state.permissions.includes('*')
    },
    hasRole: state => {
      return (code: string) => state.roles.some(r => r.code === code)
    },
    isSuperAdmin: state => {
      return state.roles.some(r => r.code === 'super_admin') || state.permissions.includes('*')
    },
  },
  actions: {
    async login(username: string, password: string, captchaId: string, captchaCode: string) {
      const result = await loginAdmin(username, password, captchaId, captchaCode)
      this.applySession(result.admin)
      return result
    },
    async loadMe() {
      const admin = await fetchAdminMe()
      this.applyAdmin(admin)
      return admin
    },
    logout() {
      this.token = ''
      this.refreshToken = ''
      this.adminId = 0
      this.username = ''
      this.nickname = ''
      this.supportStatus = 'offline'
      this.passwordMustChange = false
      this.roles = []
      this.permissions = []
      clearAuthStorage('admin')
      localStorage.removeItem('admin_support_status')
      localStorage.removeItem('admin_password_must_change')
    },
    syncFromStorage() {
      this.token = ''
      this.refreshToken = ''
      this.adminId = Number(localStorage.getItem('admin_id') || 0)
      this.username = localStorage.getItem('admin_username') || ''
      this.supportStatus = (localStorage.getItem('admin_support_status') || 'offline') as
        | 'online'
        | 'offline'
        | 'busy'
      this.passwordMustChange = localStorage.getItem('admin_password_must_change') === 'true'
    },
    applySession(admin: AdminUser) {
      this.token = ''
      this.refreshToken = ''
      this.applyAdmin(admin)
    },
    applyAdmin(admin: AdminUser) {
      this.adminId = admin.id
      this.username = admin.username
      this.nickname = admin.nickname
      this.supportStatus = admin.support_status || 'offline'
      this.passwordMustChange = admin.password_must_change
      this.roles = admin.roles || []
      this.permissions = admin.permissions || []
      localStorage.setItem('admin_id', String(admin.id))
      localStorage.setItem('admin_username', admin.username)
      localStorage.setItem('admin_support_status', admin.support_status || 'offline')
      localStorage.setItem('admin_password_must_change', String(admin.password_must_change))
    },
    setSupportStatus(status: 'online' | 'offline' | 'busy') {
      this.supportStatus = status
      localStorage.setItem('admin_support_status', status)
    },
  },
})
