import type {
  IChatRequest,
  IChatResponse,
  ICapabilitiesResponse,
  IConversation,
  IApiError,
} from './types'

const API_BASE = '/api/v1/portal'

class ApiClient {
  private baseUrl: string

  constructor(baseUrl: string = API_BASE) {
    this.baseUrl = baseUrl
  }

  private async request<T>(
    path: string,
    options: RequestInit = {}
  ): Promise<T> {
    const url = `${this.baseUrl}${path}`
    const headers: HeadersInit = {
      'Content-Type': 'application/json',
      ...options.headers,
    }

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

    if (!response.ok) {
      const error: IApiError = {
        status: response.status,
        message: response.statusText,
      }
      try {
        const body = await response.json()
        error.detail = body.detail ?? body.message
        error.message = error.detail ?? error.message
      } catch {
        // response body is not JSON, use status text
      }
      throw error
    }

    return response.json() as Promise<T>
  }

  /** Send a chat message via REST API */
  async chat(request: IChatRequest): Promise<IChatResponse> {
    return this.request<IChatResponse>('/chat', {
      method: 'POST',
      body: JSON.stringify(request),
    })
  }

  /** Get all available capabilities */
  async getCapabilities(): Promise<ICapabilitiesResponse> {
    return this.request<ICapabilitiesResponse>('/capabilities')
  }

  /** Get conversation list */
  async getConversations(): Promise<IConversation[]> {
    return this.request<IConversation[]>('/conversations')
  }

  /** Get a single conversation by ID */
  async getConversation(id: string): Promise<IConversation> {
    return this.request<IConversation>(`/conversations/${id}`)
  }

  /** Create a WebSocket connection for real-time chat */
  createWebSocket(): WebSocket {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
    const host = window.location.host
    return new WebSocket(`${protocol}//${host}${this.baseUrl}/ws`)
  }
}

export const apiClient = new ApiClient()
export { ApiClient }
