/**
 * BYOEH (Erwartungshorizont) API
 *
 * Split from api.ts for file size compliance.
 */

import { apiCall, getAuthToken } from './api'
import type {
  Erwartungshorizont, EHRAGResult, EHAuditEntry, EHKeyShare,
  SharedEHInfo, LinkedEHInfo, PendingInvitationInfo, SentInvitationInfo,
  EHAccessChain,
} from './api-eh-types'

export const ehApi = {
  listEH: (params?: { subject?: string; year?: number }): Promise<Erwartungshorizont[]> => {
    const query = new URLSearchParams()
    if (params?.subject) query.append('subject', params.subject)
    if (params?.year) query.append('year', params.year.toString())
    const queryStr = query.toString()
    return apiCall(`/eh${queryStr ? `?${queryStr}` : ''}`)
  },

  getEH: (id: string): Promise<Erwartungshorizont> => apiCall(`/eh/${id}`),

  uploadEH: async (formData: FormData): Promise<Erwartungshorizont> => {
    const token = getAuthToken()
    const headers: Record<string, string> = {}
    if (token) headers['Authorization'] = `Bearer ${token}`
    const response = await fetch('/api/v1/eh/upload', { method: 'POST', headers, body: formData })
    if (!response.ok) {
      const error = await response.json().catch(() => ({ detail: 'Upload failed' }))
      throw new Error(error.detail || `HTTP ${response.status}`)
    }
    return response.json()
  },

  deleteEH: (id: string): Promise<{ status: string; id: string }> =>
    apiCall(`/eh/${id}`, { method: 'DELETE' }),

  indexEH: (id: string, passphrase: string): Promise<{ status: string; id: string; chunk_count: number }> =>
    apiCall(`/eh/${id}/index`, { method: 'POST', body: JSON.stringify({ passphrase }) }),

  ragQuery: (params: { query_text: string; passphrase: string; subject?: string; limit?: number; rerank?: boolean }): Promise<EHRAGResult> =>
    apiCall('/eh/rag-query', { method: 'POST', body: JSON.stringify({ query_text: params.query_text, passphrase: params.passphrase, subject: params.subject, limit: params.limit ?? 5, rerank: params.rerank ?? false }) }),

  getAuditLog: (ehId?: string, limit?: number): Promise<EHAuditEntry[]> => {
    const query = new URLSearchParams()
    if (ehId) query.append('eh_id', ehId)
    if (limit) query.append('limit', limit.toString())
    const queryStr = query.toString()
    return apiCall(`/eh/audit-log${queryStr ? `?${queryStr}` : ''}`)
  },

  getRightsText: (): Promise<{ text: string; version: string }> => apiCall('/eh/rights-text'),

  getQdrantStatus: (): Promise<{ name: string; vectors_count: number; points_count: number; status: string }> =>
    apiCall('/eh/qdrant-status'),

  // Key Sharing
  shareEH: (ehId: string, params: { user_id: string; role: 'second_examiner' | 'third_examiner' | 'supervisor' | 'department_head'; encrypted_passphrase: string; passphrase_hint?: string; klausur_id?: string }): Promise<{ status: string; share_id: string; eh_id: string; shared_with: string; role: string }> =>
    apiCall(`/eh/${ehId}/share`, { method: 'POST', body: JSON.stringify(params) }),

  listShares: (ehId: string): Promise<EHKeyShare[]> => apiCall(`/eh/${ehId}/shares`),

  revokeShare: (ehId: string, shareId: string): Promise<{ status: string; share_id: string }> =>
    apiCall(`/eh/${ehId}/shares/${shareId}`, { method: 'DELETE' }),

  getSharedWithMe: (): Promise<SharedEHInfo[]> => apiCall('/eh/shared-with-me'),

  linkToKlausur: (ehId: string, klausurId: string): Promise<{ status: string; link_id: string; eh_id: string; klausur_id: string }> =>
    apiCall(`/eh/${ehId}/link-klausur`, { method: 'POST', body: JSON.stringify({ klausur_id: klausurId }) }),

  unlinkFromKlausur: (ehId: string, klausurId: string): Promise<{ status: string; eh_id: string; klausur_id: string }> =>
    apiCall(`/eh/${ehId}/link-klausur/${klausurId}`, { method: 'DELETE' }),

  // Invitation Flow
  inviteToEH: (ehId: string, params: { invitee_email: string; invitee_id?: string; role: 'second_examiner' | 'third_examiner' | 'supervisor' | 'department_head' | 'fachvorsitz'; klausur_id?: string; message?: string; expires_in_days?: number }): Promise<{ status: string; invitation_id: string; eh_id: string; invitee_email: string; role: string; expires_at: string; eh_title: string }> =>
    apiCall(`/eh/${ehId}/invite`, { method: 'POST', body: JSON.stringify(params) }),

  getPendingInvitations: (): Promise<PendingInvitationInfo[]> => apiCall('/eh/invitations/pending'),

  getSentInvitations: (): Promise<SentInvitationInfo[]> => apiCall('/eh/invitations/sent'),

  acceptInvitation: (invitationId: string, encryptedPassphrase: string): Promise<{ status: string; share_id: string; eh_id: string; role: string; klausur_id: string | null }> =>
    apiCall(`/eh/invitations/${invitationId}/accept`, { method: 'POST', body: JSON.stringify({ encrypted_passphrase: encryptedPassphrase }) }),

  declineInvitation: (invitationId: string): Promise<{ status: string; invitation_id: string; eh_id: string }> =>
    apiCall(`/eh/invitations/${invitationId}/decline`, { method: 'POST' }),

  revokeInvitation: (invitationId: string): Promise<{ status: string; invitation_id: string; eh_id: string }> =>
    apiCall(`/eh/invitations/${invitationId}`, { method: 'DELETE' }),

  getAccessChain: (ehId: string): Promise<EHAccessChain> => apiCall(`/eh/${ehId}/access-chain`),
}

export const klausurEHApi = {
  getLinkedEH: (klausurId: string): Promise<LinkedEHInfo[]> => apiCall(`/klausuren/${klausurId}/linked-eh`),
}
