import { apiClient } from './client'
import type { ApiResponse } from '@/types/api'

/**
 * External KB Access API
 *
 * Manages API keys that grant external consumers (e.g. BoostCalendar)
 * scoped access to the site's Knowledge Base via /kb/* endpoints.
 *
 * Security note: the raw key is returned ONCE on creation and is never
 * stored or retrievable afterwards (only a SHA-256 hash is persisted).
 */

export interface ExternalKBKey {
  id: string
  label: string
  allowed_consumers: string[]
  ip_allowlist: string[]
  scopes: string[]
  max_top_k: number
  rate_limit_per_min: number
  export_enabled: boolean
  retrieve_enabled: boolean
  enabled: boolean
  created_at: string
  last_used_at: string | null
}

export interface CreateExternalKBKeyInput {
  label: string
  allowed_consumers?: string[]
  ip_allowlist?: string[]
  scopes?: string[]
  max_top_k?: number
  rate_limit_per_min?: number
  export_enabled?: boolean
  retrieve_enabled?: boolean
}

export interface UpdateExternalKBKeyInput extends Partial<CreateExternalKBKeyInput> {
  enabled?: boolean
}

export const externalKBApi = {
  /**
   * List all external KB keys (hashes are never included).
   */
  async listKeys(): Promise<ApiResponse<{ keys: ExternalKBKey[] }>> {
    return apiClient.get<ApiResponse<{ keys: ExternalKBKey[] }>>('kb/keys')
  },

  /**
   * Create a key. The response includes raw_key exactly once.
   */
  async createKey(
    input: CreateExternalKBKeyInput
  ): Promise<ApiResponse<{ key: ExternalKBKey; raw_key: string }>> {
    return apiClient.post<ApiResponse<{ key: ExternalKBKey; raw_key: string }>>('kb/keys', input)
  },

  /**
   * Update a key's specification or enabled state.
   */
  async updateKey(
    id: string,
    input: UpdateExternalKBKeyInput
  ): Promise<ApiResponse<{ key: ExternalKBKey }>> {
    return apiClient.put<ApiResponse<{ key: ExternalKBKey }>>(`kb/keys/${encodeURIComponent(id)}`, input)
  },

  /**
   * Delete a key permanently.
   */
  async deleteKey(id: string): Promise<ApiResponse<{ deleted: boolean }>> {
    return apiClient.delete<ApiResponse<{ deleted: boolean }>>(`kb/keys/${encodeURIComponent(id)}`)
  },
}
