import type {
  DashboardStatsResponse,
  DashboardTrendResponse,
  AccountListResponse,
  AccountResponse,
  CreateAccountPayload,
  OAuthCreatePayload,
  GroupResponse,
  ProxyResponse,
  TestAccountResponse,
} from './types'
import type { AccountListParams } from '../types'

// 使用后端代理 API 来避免 CORS 问题
const PROXY_BASE = 'http://localhost:8088/api/s2a/proxy'

export class S2AClient {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  constructor(_config: { baseUrl: string; apiKey: string }) {
    // 不再使用直接配置，通过后端代理
  }

  private async request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
    // 将 /api/v1/admin/* 转换为代理路径
    const proxyEndpoint = endpoint.replace('/api/v1/admin', '')
    const url = `${PROXY_BASE}${proxyEndpoint}`

    const headers: HeadersInit = {
      'Content-Type': 'application/json',
      ...options.headers,
    }

    const response = await fetch(url, {
      ...options,
      headers,
    })

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}))
      throw new Error(
        errorData.message || errorData.error || `HTTP ${response.status}: ${response.statusText}`
      )
    }

    return response.json()
  }

  // Dashboard APIs
  async getDashboardStats(): Promise<DashboardStatsResponse> {
    return this.request<DashboardStatsResponse>('/dashboard/stats')
  }

  async getDashboardTrend(granularity: 'day' | 'hour' = 'day'): Promise<DashboardTrendResponse> {
    return this.request<DashboardTrendResponse>(
      `/dashboard/trend?granularity=${granularity}`
    )
  }

  // Account APIs
  async getAccounts(params: AccountListParams = {}): Promise<AccountListResponse> {
    const searchParams = new URLSearchParams()
    if (params.page) searchParams.set('page', params.page.toString())
    if (params.page_size) searchParams.set('page_size', params.page_size.toString())
    if (params.platform) searchParams.set('platform', params.platform)
    if (params.type) searchParams.set('type', params.type)
    if (params.status) searchParams.set('status', params.status)
    if (params.search) searchParams.set('search', params.search)

    const queryString = searchParams.toString()
    const endpoint = `/accounts${queryString ? `?${queryString}` : ''}`
    return this.request<AccountListResponse>(endpoint)
  }

  async getAccount(id: number): Promise<AccountResponse> {
    return this.request<AccountResponse>(`/accounts/${id}`)
  }

  async createAccount(data: CreateAccountPayload): Promise<AccountResponse> {
    return this.request<AccountResponse>('/accounts', {
      method: 'POST',
      body: JSON.stringify(data),
    })
  }

  async createFromOAuth(data: OAuthCreatePayload): Promise<AccountResponse> {
    return this.request<AccountResponse>('/openai/create-from-oauth', {
      method: 'POST',
      body: JSON.stringify(data),
    })
  }

  async updateAccount(id: number, data: Partial<CreateAccountPayload>): Promise<AccountResponse> {
    return this.request<AccountResponse>(`/accounts/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data),
    })
  }

  async deleteAccount(id: number): Promise<void> {
    await this.request<void>(`/accounts/${id}`, {
      method: 'DELETE',
    })
  }

  async testAccount(id: number): Promise<TestAccountResponse> {
    return this.request<TestAccountResponse>(`/accounts/${id}/test`, {
      method: 'POST',
    })
  }

  async refreshAccountToken(id: number): Promise<AccountResponse> {
    return this.request<AccountResponse>(`/accounts/${id}/refresh`, {
      method: 'POST',
    })
  }

  async clearAccountError(id: number): Promise<AccountResponse> {
    return this.request<AccountResponse>(`/accounts/${id}/clear-error`, {
      method: 'POST',
    })
  }

  // Group APIs
  async getGroups(): Promise<GroupResponse[]> {
    const response = await this.request<{ data: GroupResponse[] }>('/groups/all')
    return response.data || []
  }

  // Proxy APIs
  async getProxies(): Promise<ProxyResponse[]> {
    const response = await this.request<{ data: ProxyResponse[] }>('/proxies/all')
    return response.data || []
  }

  async testProxy(id: number): Promise<TestAccountResponse> {
    return this.request<TestAccountResponse>(`/proxies/${id}/test`, {
      method: 'POST',
    })
  }

  // Connection test
  async testConnection(): Promise<boolean> {
    try {
      await this.getDashboardStats()
      return true
    } catch {
      return false
    }
  }
}

// 创建默认客户端实例的工厂函数
export function createS2AClient(baseUrl: string, apiKey: string): S2AClient {
  return new S2AClient({ baseUrl, apiKey })
}
