/**
 * Admin Sora API
 * 管理员 Sora 统计和用户配额管理接口
 */

import { apiClient } from '../client'
import type { BasePaginationResponse } from '@/types'

export interface SoraUserStats {
  user_id: number
  username: string
  email: string
  quota_bytes: number
  used_bytes: number
  available_bytes: number
  quota_source: string
  generations_count: number
  active_count: number
  total_file_size_bytes: number
}

export interface SoraSystemStats {
  total_users: number
  total_generations: number
  total_storage_bytes: number
  active_generations: number
  by_status: Record<string, number>
  by_model: Record<string, number>
}

export interface SoraGenerationAdmin {
  id: number
  user_id: number
  username: string
  email: string
  model: string
  prompt: string
  media_type: string
  status: string
  storage_type: string
  media_url: string
  file_size_bytes: number
  error_message: string
  created_at: string
  completed_at: string | null
}

const soraAdminAPI = {
  /**
   * 获取 Sora 系统统计
   */
  async getSystemStats(): Promise<SoraSystemStats> {
    const { data } = await apiClient.get<{ data: SoraSystemStats }>('/admin/sora/stats')
    return data.data
  },

  /**
   * 获取用户 Sora 使用统计列表
   */
  async listUserStats(params?: {
    page?: number
    page_size?: number
    search?: string
    sort_by?: string
    sort_order?: string
  }): Promise<BasePaginationResponse<SoraUserStats>> {
    const { data } = await apiClient.get<BasePaginationResponse<SoraUserStats>>('/admin/sora/users', { params })
    return data
  },

  /**
   * 获取 Sora 生成记录列表（管理员视角）
   */
  async listGenerations(params?: {
    page?: number
    page_size?: number
    user_id?: number
    status?: string
    model?: string
    sort_by?: string
    sort_order?: string
  }): Promise<BasePaginationResponse<SoraGenerationAdmin>> {
    const { data } = await apiClient.get<BasePaginationResponse<SoraGenerationAdmin>>('/admin/sora/generations', { params })
    return data
  },

  /**
   * 删除用户的 Sora 存储空间（管理员操作）
   */
  async clearUserStorage(userId: number): Promise<void> {
    await apiClient.delete(`/admin/sora/users/${userId}/storage`)
  },
}

export default soraAdminAPI
