import axios from 'axios'

const api = axios.create({
  baseURL: '/api/admin',
  withCredentials: true,
})

api.interceptors.response.use(
  (r) => r,
  (err) => {
    if (err.response?.status === 401 && !window.location.pathname.startsWith('/login')) {
      window.location.href = '/login'
    }
    return Promise.reject(err)
  },
)

export default api

export interface Provider {
  id: number
  name: string
  type: string
  category: string
  base_url: string
  allowed_endpoints_json: string
  endpoint_paths_json: string
  status: string
  enabled?: boolean
  keys?: ProviderKey[]
  models?: ModelEntry[]
}

export interface ProviderKey {
  id: number
  provider_id: number
  name: string
  weight: number
  models_json: string
  enabled: boolean
  max_requests_per_day: number
  max_tokens_per_day: number
  requests_today: number
  tokens_today: number
}

export interface ModelEntry {
  id: number
  provider_id: number
  model_id: string
  alias?: string
  display_name: string
  workflow_type?: string
  workflow_json?: string
  input_binding_json?: string
  version_hash?: string
  enabled: boolean
  created_at?: string
}

export interface IngressKey {
  id: number
  name: string
  prefix: string
  protocol: 'text' | 'image'
  enabled: boolean
  budget_limit: number
  budget_used: number
  rate_limit_rpm: number
  rate_limit_tpm: number
  allowed_providers_json: string
  allowed_models_json: string
  request_count: number
  token_count: number
}

export interface IPRule {
  id: number
  cidr: string
  type: 'allow' | 'deny'
  scope: 'admin' | 'proxy' | 'all'
  enabled: boolean
}

export interface DashboardOverview {
  total_requests_24h: number
  total_tokens_24h: number
  error_rate: number
  active_ingress_keys: number
  providers: number
}

export interface ProviderModelUsage {
  provider_id: number
  provider_name: string
  model: string
  request_count: number
  token_count: number
  cost: number
}

export interface ClientIPUsage {
  client_ip: string
  request_count: number
  token_count: number
  cost: number
}

export interface RequestTrendBucket {
  hour: string
  requests: number
  errors: number
  tokens: number
}
