/**
 * 角色管理服务
 */

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

export interface CreateRoleRequest {
  roleCode: string
  roleName: string
  roleLevel: number
  dataScope: 'ALL' | 'DEPARTMENT' | 'OWN'
  description?: string
}

export interface UpdateRoleRequest extends Partial<CreateRoleRequest> {
  id: number
  status?: number
}

export interface AssignPermissionsRequest {
  roleId: number
  permissionIds: number[]
}

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

/**
 * 角色管理服务类
 */
class RoleService {
  private baseUrl = '/api'

  /**
   * 获取所有角色列表
   */
  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 getRoleById(id: number): Promise<RoleInfo | null> {
    const response = await fetch(`${this.baseUrl}/roles/${id}`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<RoleInfo>
    if (result.code !== 200) {
      return null
    }
    return result.data
  }

  /**
   * 创建角色
   */
  async createRole(data: CreateRoleRequest): Promise<number> {
    const response = await fetch(`${this.baseUrl}/roles`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify(data)
    })
    const result = await response.json() as ApiResponse<number>
    if (result.code !== 200) {
      throw new Error(result.message || '创建角色失败')
    }
    return result.data
  }

  /**
   * 更新角色
   */
  async updateRole(data: UpdateRoleRequest): Promise<void> {
    const response = await fetch(`${this.baseUrl}/roles/${data.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify(data)
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '更新角色失败')
    }
  }

  /**
   * 删除角色
   */
  async deleteRole(id: number): Promise<void> {
    const response = await fetch(`${this.baseUrl}/roles/${id}`, {
      method: 'DELETE',
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '删除角色失败')
    }
  }

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

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

  /**
   * 获取所有权限列表
   */
  async getAllPermissions(): 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 getCurrentUser(): Promise<{ id: number; username: string; roles: string[] }> {
    const response = await fetch(`${this.baseUrl}/auth/current`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<any>
    if (result.code !== 200) {
      throw new Error(result.message || '获取用户信息失败')
    }
    return result.data
  }
}

export const roleService = new RoleService()
export default roleService
