import { ref } from 'vue'

const BASE_URL = 'http://0.0.0.0:8001/api/v1/api-management'

export interface ApiEndpoint {
  id: string
  name: string
  description: string
  path: string
  method: string
  algorithm_id: string
  algorithm_name: string
  version_id: string
  version: string
  service_id: string | null
  status: string
  is_public: boolean
  call_count: string
  success_count: string
  error_count: string
  avg_response_time: string
  created_at: string
  updated_at: string | null
  last_called_at: string | null
}

export interface ApiStats {
  total_endpoints: number
  active_endpoints: number
  total_calls: string
  total_success: string
  total_errors: string
  avg_response_time: string
}

export const apiManagementService = {
  async getApiEndpoints(algorithmId?: string, status?: string): Promise<{ endpoints: ApiEndpoint[], total: number }> {
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('未登录')
    }

    const params = new URLSearchParams()
    if (algorithmId) params.append('algorithm_id', algorithmId)
    if (status) params.append('status', status)

    const response = await fetch(`${BASE_URL}/endpoints?${params.toString()}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })

    if (!response.ok) {
      throw new Error('获取API端点列表失败')
    }

    return await response.json()
  },

  async getApiEndpoint(endpointId: string): Promise<ApiEndpoint> {
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('未登录')
    }

    const response = await fetch(`${BASE_URL}/endpoints/${endpointId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })

    if (!response.ok) {
      throw new Error('获取API端点详情失败')
    }

    return await response.json()
  },

  async createApiEndpoint(data: {
    name: string
    description: string
    path: string
    method: string
    algorithm_id: string
    version_id: string
    service_id?: string
    requires_auth: boolean
    allowed_roles: string[]
    rate_limit?: Record<string, any>
    is_public: boolean
    config: Record<string, any>
  }): Promise<ApiEndpoint> {
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('未登录')
    }

    const response = await fetch(`${BASE_URL}/endpoints`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify(data)
    })

    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.detail || '创建API端点失败')
    }

    return await response.json()
  },

  async updateApiEndpoint(endpointId: string, data: Partial<{
    name: string
    description: string
    path: string
    method: string
    requires_auth: boolean
    allowed_roles: string[]
    rate_limit?: Record<string, any>
    is_public: boolean
    config: Record<string, any>
    status: string
  }>): Promise<ApiEndpoint> {
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('未登录')
    }

    const response = await fetch(`${BASE_URL}/endpoints/${endpointId}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify(data)
    })

    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.detail || '更新API端点失败')
    }

    return await response.json()
  },

  async deleteApiEndpoint(endpointId: string): Promise<{ success: boolean; message: string }> {
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('未登录')
    }

    const response = await fetch(`${BASE_URL}/endpoints/${endpointId}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })

    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.detail || '删除API端点失败')
    }

    return await response.json()
  },

  async getApiStats(): Promise<ApiStats> {
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('未登录')
    }

    const response = await fetch(`${BASE_URL}/stats`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })

    if (!response.ok) {
      throw new Error('获取API统计信息失败')
    }

    return await response.json()
  },

  async testApiEndpoint(endpointId: string, payload: Record<string, any>): Promise<{
    success: boolean
    result?: any
    response_time: number
    message?: string
    error?: string
  }> {
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('未登录')
    }

    const response = await fetch(`${BASE_URL}/endpoints/${endpointId}/test`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify(payload)
    })

    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.detail || '测试API端点失败')
    }

    return await response.json()
  },

  async syncApiEndpoints(): Promise<{ success: boolean; message: string }> {
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('未登录')
    }

    const response = await fetch('http://0.0.0.0:8001/api/v1/services/sync-api-endpoints', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })

    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.detail || '同步API端点失败')
    }

    return await response.json()
  }
}