/** Document API client — thin wrapper over /api/v1/documents endpoints. */

import { BaseApiClient, getDynamicBaseURL } from './base'

export interface IDocumentMeta {
  id: string
  filename: string
  stored_name: string
  format: string
  size: number
  conversation_id: string
  created_at: string
  download_url: string
}

/**
 * Runtime guard for IDocumentMeta — validates the minimum fields required
 * for the documents store to function safely (#8).
 * ponytail: checks only the keys the store actually reads; full schema
 * validation belongs at the API boundary, not in the WS event handler.
 */
export function isDocumentMeta(value: unknown): value is IDocumentMeta {
  if (typeof value !== 'object' || value === null) return false
  const v = value as Record<string, unknown>
  return (
    typeof v.id === 'string' &&
    typeof v.filename === 'string' &&
    typeof v.conversation_id === 'string' &&
    typeof v.format === 'string'
  )
}

export interface ICreateDocumentRequest {
  format: 'word' | 'excel' | 'pdf'
  content: string
  conversation_id: string
  filename?: string
  template?: string
  template_data?: Record<string, unknown>
}

const API_BASE = '/api/v1/documents'

class DocumentApiClient extends BaseApiClient {
  constructor(baseUrl: string = API_BASE) {
    super(baseUrl)
  }

  /** Create a document from Markdown content or template */
  async create(request: ICreateDocumentRequest): Promise<{ success: boolean; document: IDocumentMeta }> {
    return this.request('/create', {
      method: 'POST',
      body: JSON.stringify(request),
    })
  }

  /** List documents for a conversation */
  async listByConversation(conversationId: string): Promise<{
    success: boolean
    documents: IDocumentMeta[]
    count: number
  }> {
    return this.request(`/conversation/${conversationId}`, { method: 'GET' })
  }

  /** Upload a .docx template file */
  async uploadTemplate(file: File): Promise<{
    success: boolean
    stored_name: string
    filename: string
    size: number
  }> {
    const formData = new FormData()
    formData.append('file', file)
    return this.request('/upload-template', {
      method: 'POST',
      body: formData,
      headers: {}, // Let browser set Content-Type for FormData
    })
  }

  /** Get the full download URL for a document */
  getDownloadUrl(doc: IDocumentMeta): string {
    const base = getDynamicBaseURL()
    const url = doc.download_url || `/api/v1/documents/download/${doc.id}`
    if (!base || url.startsWith('http')) return url
    return `${base}${url}`
  }
}

export const documentApi = new DocumentApiClient()
