// =============================================================================
// S2A API 响应类型
// 基于 requirements.md Appendix A2 定义
// =============================================================================

// -----------------------------------------------------------------------------
// Dashboard 相关接口响应
// -----------------------------------------------------------------------------

/**
 * Dashboard Stats 响应
 * API: GET /api/v1/admin/dashboard/stats
 * 获取号池统计（账号数、请求数、Token消耗等）
 */
export interface DashboardStatsResponse {
  total_accounts: number
  normal_accounts: number
  error_accounts: number
  ratelimit_accounts: number
  overload_accounts: number
  today_requests: number
  today_tokens: number
  today_cost: number
  total_requests: number
  total_tokens: number
  total_cost: number
  rpm: number
  tpm: number
}

/**
 * Dashboard Trend 响应
 * API: GET /api/v1/admin/dashboard/trend
 * 获取使用趋势（支持 granularity=day/hour）
 */
export interface DashboardTrendResponse {
  data: TrendDataPoint[]
}

export interface TrendDataPoint {
  date: string
  requests: number
  tokens: number
  cost: number
}

/**
 * Dashboard Models 响应
 * API: GET /api/v1/admin/dashboard/models
 * 获取模型使用统计
 */
export interface DashboardModelsResponse {
  data: ModelUsageStats[]
}

export interface ModelUsageStats {
  model: string
  requests: number
  tokens: number
  cost: number
  percentage: number
}

/**
 * Dashboard Users Trend 响应
 * API: GET /api/v1/admin/dashboard/users-trend
 * 获取用户使用趋势
 */
export interface DashboardUsersTrendResponse {
  data: UsersTrendDataPoint[]
}

export interface UsersTrendDataPoint {
  date: string
  active_users: number
  new_users: number
  total_users: number
}

// -----------------------------------------------------------------------------
// 账号管理接口响应
// -----------------------------------------------------------------------------

/**
 * 账号列表响应
 * API: GET /api/v1/admin/accounts
 * 获取账号列表（支持分页、筛选）
 */
export interface AccountListResponse {
  data: AccountResponse[]
  total: number
  page: number
  page_size: number
}

/**
 * 单个账号响应
 * API: GET /api/v1/admin/accounts/:id
 * 对应 requirements.md A5 Account 数据结构
 */
export interface AccountResponse {
  id: number
  name: string
  notes?: string
  platform: 'openai' | 'anthropic' | 'gemini'
  type: 'oauth' | 'access_token' | 'apikey' | 'setup-token'
  credentials: Record<string, unknown>
  extra?: Record<string, unknown>
  proxy_id?: number
  concurrency: number
  priority: number
  rate_multiplier?: number
  status: 'active' | 'inactive' | 'error'
  error_message?: string
  schedulable: boolean
  last_used_at?: string
  expires_at?: string
  auto_pause_on_expired: boolean
  created_at: string
  updated_at: string
  current_concurrency?: number
  current_window_cost?: number
  active_sessions?: number
}

/**
 * 账号统计响应
 * API: GET /api/v1/admin/accounts/:id/stats
 * 获取账号使用统计
 */
export interface AccountStatsResponse {
  account_id: number
  total_requests: number
  total_tokens: number
  total_cost: number
  today_requests: number
  today_tokens: number
  today_cost: number
  last_used_at?: string
  error_count: number
  success_rate: number
}

/**
 * 创建账号请求
 * API: POST /api/v1/admin/accounts
 * 对应 requirements.md A4 access_token 类型账号
 */
export interface CreateAccountPayload {
  name: string
  platform: 'openai' | 'anthropic' | 'gemini'
  type: 'access_token'
  credentials: {
    access_token: string
    refresh_token?: string
    email?: string
  }
  concurrency?: number
  priority?: number
  group_ids?: number[]
  proxy_id?: number | null
  auto_pause_on_expired?: boolean
}

/**
 * 批量更新账号请求
 * API: POST /api/v1/admin/accounts/bulk-update
 */
export interface BulkUpdateAccountsPayload {
  ids: number[]
  updates: {
    status?: 'active' | 'inactive'
    concurrency?: number
    priority?: number
    group_ids?: number[]
    proxy_id?: number | null
  }
}

/**
 * 批量更新账号响应
 */
export interface BulkUpdateAccountsResponse {
  success: boolean
  updated_count: number
  failed_count: number
  errors?: string[]
}

// -----------------------------------------------------------------------------
// OpenAI OAuth 接口响应
// -----------------------------------------------------------------------------

/**
 * OAuth 创建账号请求
 * API: POST /api/v1/admin/openai/create-from-oauth
 * 对应 requirements.md A4 OAuth 类型账号
 */
export interface OAuthCreatePayload {
  session_id: string
  code: string
  name?: string
  concurrency?: number
  priority?: number
  group_ids?: number[]
  proxy_id?: number | null
}

/**
 * 生成 OAuth 授权 URL 请求
 * API: POST /api/v1/admin/openai/generate-auth-url
 */
export interface GenerateAuthUrlPayload {
  redirect_uri?: string
}

/**
 * 生成 OAuth 授权 URL 响应
 */
export interface GenerateAuthUrlResponse {
  auth_url: string
  session_id: string
}

/**
 * 交换授权码请求
 * API: POST /api/v1/admin/openai/exchange-code
 */
export interface ExchangeCodePayload {
  session_id: string
  code: string
}

/**
 * 交换授权码响应
 */
export interface ExchangeCodeResponse {
  access_token: string
  refresh_token?: string
  expires_in?: number
  token_type: string
}

/**
 * 刷新 Token 请求
 * API: POST /api/v1/admin/openai/refresh-token
 */
export interface RefreshTokenPayload {
  refresh_token: string
}

/**
 * 刷新 Token 响应
 */
export interface RefreshTokenResponse {
  access_token: string
  refresh_token?: string
  expires_in?: number
  token_type: string
}

// -----------------------------------------------------------------------------
// 分组管理接口响应
// -----------------------------------------------------------------------------

/**
 * 分组响应
 * API: GET /api/v1/admin/groups, GET /api/v1/admin/groups/all
 */
export interface GroupResponse {
  id: number
  name: string
  description?: string
  created_at: string
  updated_at: string
}

/**
 * 分组统计响应
 * API: GET /api/v1/admin/groups/:id/stats
 */
export interface GroupStatsResponse {
  group_id: number
  total_accounts: number
  active_accounts: number
  error_accounts: number
  total_requests: number
  total_tokens: number
  total_cost: number
}

// -----------------------------------------------------------------------------
// 代理管理接口响应
// -----------------------------------------------------------------------------

/**
 * 代理响应
 * API: GET /api/v1/admin/proxies, GET /api/v1/admin/proxies/all
 */
export interface ProxyResponse {
  id: number
  name: string
  url: string
  status: 'active' | 'inactive' | 'error'
  created_at: string
  updated_at: string
}

/**
 * 测试代理/账号响应
 * API: POST /api/v1/admin/proxies/:id/test, POST /api/v1/admin/accounts/:id/test
 */
export interface TestAccountResponse {
  success: boolean
  message?: string
  latency?: number
}

// -----------------------------------------------------------------------------
// 运维监控接口响应
// -----------------------------------------------------------------------------

/**
 * 并发统计响应
 * API: GET /api/v1/admin/ops/concurrency
 */
export interface OpsConcurrencyResponse {
  total_concurrency: number
  used_concurrency: number
  available_concurrency: number
  accounts: AccountConcurrencyInfo[]
}

export interface AccountConcurrencyInfo {
  account_id: number
  account_name: string
  max_concurrency: number
  current_concurrency: number
}

/**
 * 账号可用性响应
 * API: GET /api/v1/admin/ops/account-availability
 */
export interface OpsAccountAvailabilityResponse {
  total_accounts: number
  available_accounts: number
  unavailable_accounts: number
  availability_rate: number
  accounts: AccountAvailabilityInfo[]
}

export interface AccountAvailabilityInfo {
  account_id: number
  account_name: string
  status: 'available' | 'unavailable' | 'rate_limited' | 'error'
  reason?: string
}

/**
 * 实时流量响应
 * API: GET /api/v1/admin/ops/realtime-traffic
 */
export interface OpsRealtimeTrafficResponse {
  current_rpm: number
  current_tpm: number
  peak_rpm: number
  peak_tpm: number
  requests_last_minute: number
  tokens_last_minute: number
}

/**
 * 运维仪表盘概览响应
 * API: GET /api/v1/admin/ops/dashboard/overview
 */
export interface OpsDashboardOverviewResponse {
  health_score: number
  total_accounts: number
  healthy_accounts: number
  warning_accounts: number
  error_accounts: number
  current_load: number
  max_load: number
  alerts: OpsAlert[]
}

export interface OpsAlert {
  id: string
  level: 'info' | 'warning' | 'error' | 'critical'
  message: string
  timestamp: string
  account_id?: number
}

/**
 * 错误趋势响应
 * API: GET /api/v1/admin/ops/dashboard/error-trend
 */
export interface OpsErrorTrendResponse {
  data: ErrorTrendDataPoint[]
}

export interface ErrorTrendDataPoint {
  date: string
  total_errors: number
  rate_limit_errors: number
  auth_errors: number
  network_errors: number
  other_errors: number
}

// =============================================================================
// ChatGPT API 响应类型
// 基于 requirements.md Requirement 1.2 定义
// =============================================================================

/**
 * 账号检查响应
 * API: GET https://chatgpt.com/backend-api/accounts/check/v4-2023-04-27
 * Headers: Authorization: Bearer {token}
 */
export interface ChatGPTCheckResponse {
  accounts: ChatGPTAccountInfo[]
}

export interface ChatGPTAccountInfo {
  account_id: string
  account: ChatGPTAccountDetails
  features: string[]
  entitlement: ChatGPTEntitlement
  last_active_subscription: ChatGPTLastActiveSubscription
  is_eligible_for_yearly_plus_subscription: boolean
}

export interface ChatGPTAccountDetails {
  account_user_id: string
  processor: {
    a001: {
      has_customer_object: boolean
    }
  }
  account_user_role: string
  plan_type: string
  is_most_recent_expired_subscription_gratis: boolean
  has_previously_paid_subscription: boolean
  name: string | null
  profile_picture_id: string | null
  profile_picture_url: string | null
  structure: string
  is_deactivated: boolean
  is_disabled: boolean
  // SAM (Security Account Management) 相关字段
  is_sam_enforced: boolean
  is_sam_enabled: boolean
  is_sam_compliant: boolean
  is_sam_grace_period: boolean
  is_sam_grace_period_expired: boolean
  is_sam_grace_period_expiring_soon: boolean
  is_sam_grace_period_expiring_today: boolean
  is_sam_grace_period_expiring_tomorrow: boolean
  is_sam_grace_period_expiring_in_two_days: boolean
  is_sam_grace_period_expiring_in_three_days: boolean
  is_sam_grace_period_expiring_in_four_days: boolean
  is_sam_grace_period_expiring_in_five_days: boolean
  is_sam_grace_period_expiring_in_six_days: boolean
  is_sam_grace_period_expiring_in_seven_days: boolean
}

export interface ChatGPTEntitlement {
  subscription_id: string | null
  has_active_subscription: boolean
  subscription_plan: string
  expires_at: string | null
}

export interface ChatGPTLastActiveSubscription {
  subscription_id: string | null
  purchase_origin_platform: string
  will_renew: boolean
}

// =============================================================================
// 通用 API 类型
// =============================================================================

/**
 * API 错误响应
 * 通用错误响应格式
 */
export interface ApiErrorResponse {
  error: string
  message?: string
  code?: string
  details?: Record<string, unknown>
}

/**
 * 分页请求参数
 */
export interface PaginationParams {
  page?: number
  page_size?: number
}

/**
 * 分页响应包装
 */
export interface PaginatedResponse<T> {
  data: T[]
  total: number
  page: number
  page_size: number
  total_pages: number
}

/**
 * 通用列表响应包装
 */
export interface ListResponse<T> {
  data: T[]
}
