/**
 * 权限服务 - 与后端权限API交互
 */

import type { AdminRole, Permission, DataScope, RoleInfo, PermissionInfo } from '../auth/roles'

export interface UserPermissions {
  userId: number
  roles: string[]
  permissions: string[]
  dataScope: DataScope
}

export interface ApiResponse<T> {
  code: number
  data: T
  message?: string
}

/**
 * 权限服务类
 */
class PermissionService {
  private baseUrl = '/api'

  /**
   * 获取当前用户权限信息
   */
  async getUserPermissions(): Promise<UserPermissions> {
    const response = await fetch(`${this.baseUrl}/permissions/current`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<UserPermissions>
    if (result.code !== 200) {
      throw new Error(result.message || '获取权限失败')
    }
    return result.data
  }

  /**
   * 检查用户是否拥有指定权限
   */
  async hasPermission(permissionCode: Permission): Promise<boolean> {
    const response = await fetch(`${this.baseUrl}/permissions/check?permissionCode=${permissionCode}`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<boolean>
    return result.code === 200 && result.data
  }

  /**
   * 检查用户是否拥有指定角色
   */
  async hasRole(roleCode: AdminRole): Promise<boolean> {
    const response = await fetch(`${this.baseUrl}/permissions/role?roleCode=${roleCode}`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<boolean>
    return result.code === 200 && result.data
  }

  /**
   * 获取用户数据权限范围
   */
  async getDataScope(): Promise<DataScope> {
    const response = await fetch(`${this.baseUrl}/permissions/datascope`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<DataScope>
    if (result.code !== 200) {
      return 'OWN' // 默认个人权限
    }
    return result.data
  }

  /**
   * 获取所有角色列表
   */
  async getRoles(): Promise<RoleInfo[]> {
    const response = await fetch(`${this.baseUrl}/roles`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<RoleInfo[]>
    if (result.code !== 200) {
      throw new Error(result.message || '获取角色列表失败')
    }
    return result.data
  }

  /**
   * 获取所有权限列表
   */
  async getPermissions(): Promise<PermissionInfo[]> {
    const response = await fetch(`${this.baseUrl}/permissions`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<PermissionInfo[]>
    if (result.code !== 200) {
      throw new Error(result.message || '获取权限列表失败')
    }
    return result.data
  }

  /**
   * 分配角色给用户
   */
  async assignRole(userId: number, roleIds: number[]): Promise<void> {
    const response = await fetch(`${this.baseUrl}/users/${userId}/roles`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ roleIds })
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '分配角色失败')
    }
  }

  /**
   * 分配权限给角色
   */
  async assignPermissions(roleId: number, permissionIds: number[]): Promise<void> {
    const response = await fetch(`${this.baseUrl}/roles/${roleId}/permissions`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ permissionIds })
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '分配权限失败')
    }
  }
}

export const permissionService = new PermissionService()
export default permissionService
