import axios from 'axios'
import { http, tokenManager } from './client'
import type { AdminStatistics, AdminUser, AdminUserDetail, PagedResult, Bookmark, AuthResponse, UserStatus } from '@/types'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api'

export const adminApi = {
  // 登录
  async login(email: string, password: string): Promise<AuthResponse> {
    const response = await axios.post<AuthResponse>(`${API_BASE_URL}/auth/login`, {
      email,
      password,
      deviceName: 'Admin Panel',
      deviceType: 'Web Admin'
    })

    if (response.data.success && response.data.accessToken) {
      tokenManager.setAccessToken(response.data.accessToken)
      tokenManager.setRefreshToken(response.data.refreshToken!)
      tokenManager.setTokenExpires(response.data.expiresAt!)
    }

    return response.data
  },

  // 登出
  async logout(): Promise<void> {
    try {
      const token = tokenManager.getAccessToken()
      if (token) {
        await axios.post(
          `${API_BASE_URL}/auth/logout`,
          {},
          { headers: { Authorization: `Bearer ${token}` } }
        )
      }
    } finally {
      tokenManager.clearTokens()
    }
  },

  // 获取统计数据
  async getStatistics() {
    return http.get<AdminStatistics>('/admin/statistics')
  },

  // 获取用户列表
  async getUsers(params: { page?: number; pageSize?: number; search?: string; status?: UserStatus }) {
    return http.get<PagedResult<AdminUser>>('/admin/users', { params })
  },

  // 获取用户详情
  async getUserDetail(id: string) {
    return http.get<AdminUserDetail>(`/admin/users/${id}`)
  },

  // 设置用户状态
  async setUserStatus(id: string, disabled: boolean) {
    return http.put(`/admin/users/${id}/status`, { disabled })
  },

  // 重置用户密码
  async resetUserPassword(id: string) {
    return http.post<string>(`/admin/users/${id}/reset-password`)
  },

  // 获取用户书签
  async getUserBookmarks(userId: string, params: { page?: number; pageSize?: number; search?: string }) {
    return http.get<PagedResult<Bookmark>>(`/admin/users/${userId}/bookmarks`, { params })
  },

  // 删除用户书签
  async deleteUserBookmark(userId: string, bookmarkId: string) {
    return http.delete(`/admin/users/${userId}/bookmarks/${bookmarkId}`)
  },

  // 强制设备下线
  async forceDeviceLogout(deviceId: string) {
    return http.post(`/admin/devices/${deviceId}/force-logout`)
  },

  // 设置设备状态
  async setDeviceStatus(deviceId: string, disabled: boolean) {
    return http.put(`/admin/devices/${deviceId}/status`, { disabled })
  }
}

