import type { AdminRole, Permission } from '../roles'
import { RolePermissions, RoleLabels } from '../roles'
import type { AuthAdapter, AuthUser, LoginResult } from '../types'

// 角色名称映射
const roleNameMap: Record<AdminRole, string> = {
  // 系统层
  'super_admin': '演示超级管理员',
  'system_admin': '演示系统管理员',
  // 管理层
  'operation_director': '演示运营总监',
  'operation_manager': '演示运营经理',
  'operation_specialist': '演示运营专员',
  'marketing_director': '演示市场总监',
  'marketing_manager': '演示市场经理',
  'marketing_specialist': '演示市场专员',
  'finance_manager': '演示财务经理',
  'finance_specialist': '演示财务专员',
  'risk_manager': '演示风控经理',
  'risk_specialist': '演示风控专员',
  'cs_manager': '演示客服主管',
  'cs_agent': '演示客服专员',
  // 审计层
  'auditor': '演示审计员',
  // 兼容
  'viewer': '演示访客'
}

const demoUser = (role: AdminRole): AuthUser => ({
  id: `demo-${role}`,
  name: roleNameMap[role] || '演示用户',
  email: 'demo@mosquito.local',
  role
})

export class DemoAuthAdapter implements AuthAdapter {
  private currentUser: AuthUser = demoUser('super_admin')

  async loginWithPassword(_username: string, _password: string): Promise<LoginResult> {
    return { user: demoUser('super_admin') }
  }

  async loginDemo(role: AdminRole = 'super_admin'): Promise<LoginResult> {
    this.currentUser = demoUser(role)
    return { user: this.currentUser }
  }

  async logout(): Promise<void> {
    this.currentUser = null as any
  }

  async switchRole(role: AdminRole): Promise<AuthUser> {
    this.currentUser = demoUser(role)
    return this.currentUser
  }

  async getCurrentUser(): Promise<AuthUser | null> {
    return this.currentUser
  }

  hasPermission(role: AdminRole, permission: Permission): boolean {
    return RolePermissions[role]?.includes(permission) ?? false
  }
}
