/**
 * Session facts API — the "What we know" CRUD surface for a FlowPilot session.
 *
 * Mirrors backend endpoints at `/api/v1/ai-sessions/{id}/facts`.
 * See FLOWPILOT-MIGRATION.md Section 5.1.
 */
import apiClient from './client'

export type SessionFactSourceType =
  | 'question'
  | 'diagnostic_check'
  | 'user_note'
  | 'ai_synthesis'

export interface SessionFact {
  id: string
  session_id: string
  text: string
  source_type: SessionFactSourceType
  source_ref: string | null
  source_summary: string | null
  created_by: string
  created_at: string
  updated_at: string
  // Server-computed: false for question/diagnostic_check (PATCH returns 403),
  // true for user_note/ai_synthesis. Drives the edit affordance in the UI.
  editable: boolean
}

export interface SessionFactCreateRequest {
  text: string
  summary?: string | null
}

export interface SessionFactUpdateRequest {
  text?: string | null
  summary?: string | null
}

export interface SessionFactPromoteRequest {
  source_type: 'question' | 'diagnostic_check' | 'ai_synthesis'
  source_ref?: string | null
  proposed_text?: string | null
  proposed_summary?: string | null
  raw_input?: string | null
}

export const sessionFactsApi = {
  async list(sessionId: string): Promise<SessionFact[]> {
    const r = await apiClient.get<{ facts: SessionFact[] }>(
      `/ai-sessions/${sessionId}/facts`,
    )
    return r.data.facts
  },

  async create(sessionId: string, data: SessionFactCreateRequest): Promise<SessionFact> {
    const r = await apiClient.post<SessionFact>(
      `/ai-sessions/${sessionId}/facts`,
      data,
    )
    return r.data
  },

  async update(
    sessionId: string,
    factId: string,
    data: SessionFactUpdateRequest,
  ): Promise<SessionFact> {
    const r = await apiClient.patch<SessionFact>(
      `/ai-sessions/${sessionId}/facts/${factId}`,
      data,
    )
    return r.data
  },

  async remove(sessionId: string, factId: string): Promise<void> {
    await apiClient.delete(`/ai-sessions/${sessionId}/facts/${factId}`)
  },

  async promote(sessionId: string, data: SessionFactPromoteRequest): Promise<SessionFact> {
    const r = await apiClient.post<SessionFact>(
      `/ai-sessions/${sessionId}/facts/promote`,
      data,
    )
    return r.data
  },
}

export default sessionFactsApi
