export type MeetingSummary = {
  id: number
  started_at: string
  ended_at: string | null
  title: string | null
}

export type Utterance = {
  id: number
  meeting_id: number
  speaker: string
  text: string
  ts: string
}

export type AnswerRecord = {
  id: number
  meeting_id: number
  question_text: string
  suggestions: string[]
  created_at: string
}

async function request<T>(url: string, options?: RequestInit): Promise<T> {
  const res = await fetch(url, {
    headers: {
      'Content-Type': 'application/json',
    },
    ...options,
  })
  if (!res.ok) {
    const data = await res.json().catch(() => ({}))
    const message = data.message || '서버 요청에 실패했습니다.'
    throw new Error(message)
  }
  return (await res.json()) as T
}

export async function fetchMeetings(): Promise<MeetingSummary[]> {
  return request<MeetingSummary[]>('/api/meetings')
}

export async function fetchMeeting(id: number): Promise<{
  meeting: MeetingSummary
  utterances: Utterance[]
  answers: AnswerRecord[]
}> {
  return request(`/api/meetings/${id}`)
}

export async function createMeeting(started_at: string): Promise<{ id: number }> {
  return request('/api/meetings', {
    method: 'POST',
    body: JSON.stringify({ started_at }),
  })
}

export async function endMeeting(
  id: number,
  ended_at: string,
  title?: string
): Promise<{ ok: true }> {
  return request(`/api/meetings/${id}/end`, {
    method: 'POST',
    body: JSON.stringify({ ended_at, title }),
  })
}

export async function saveUtterance(id: number, text: string, ts: string) {
  return request(`/api/meetings/${id}/utterances`, {
    method: 'POST',
    body: JSON.stringify({ text, ts }),
  })
}

export async function saveAnswers(
  id: number,
  question_text: string,
  suggestions: string[]
) {
  return request(`/api/meetings/${id}/answers`, {
    method: 'POST',
    body: JSON.stringify({ question_text, suggestions }),
  })
}

export async function deleteMeetings(ids: number[]) {
  return request('/api/meetings', {
    method: 'DELETE',
    body: JSON.stringify({ ids }),
  })
}

export async function fetchAnswerSuggestions(context: string[], question: string) {
  return request<{ suggestions: string[] }>('/api/answer_suggestions', {
    method: 'POST',
    body: JSON.stringify({ context, question }),
  })
}
