import { apiGet, apiPost, apiPut, apiPutKeepalive } from './http'
import type { PageData, QuizAttempt, QuizAttemptHistory, WrongQuestion } from '@/types/api'

export function fetchResources() {
  return apiGet('/api/app/resources')
}

export function fetchBankTags(bankId: number) {
  return apiGet<Array<{ id: number; name: string }>>(`/api/app/banks/${bankId}/tags`)
}

export function fetchBankAttemptHistory(bankId: number, params?: Record<string, unknown>) {
  return apiGet<PageData<QuizAttemptHistory>>(`/api/app/banks/${bankId}/attempts/history`, params)
}

export function startBankAttempt(bankId: number, payload: Record<string, unknown>) {
  return apiPost<QuizAttempt>(`/api/app/banks/${bankId}/attempts`, payload)
}

export function startPaperAttempt(paperId: number) {
  return apiPost<QuizAttempt>(`/api/app/papers/${paperId}/attempts`)
}

export function fetchAttempt(attemptId: number) {
  return apiGet<QuizAttempt>(`/api/app/attempts/${attemptId}`)
}

export function answerQuestion(attemptId: number, payload: { question_id: number; answer: Array<number | string>; duration_seconds?: number }) {
  return apiPost(`/api/app/attempts/${attemptId}/answer`, payload)
}

export function updateAttemptPosition(attemptId: number, currentIndex: number) {
  return apiPut<QuizAttempt>(`/api/app/attempts/${attemptId}/position`, { current_index: currentIndex })
}

export function updateAttemptPositionKeepalive(attemptId: number, currentIndex: number) {
  return apiPutKeepalive(`/api/app/attempts/${attemptId}/position`, { current_index: currentIndex })
}

export function submitAttempt(attemptId: number) {
  return apiPost<QuizAttempt>(`/api/app/attempts/${attemptId}/submit`)
}

export function fetchWrongQuestions(params?: Record<string, unknown>) {
  return apiGet<PageData<WrongQuestion>>('/api/app/wrong-questions', params)
}

export function masterWrongQuestion(wrongQuestionId: number) {
  return apiPost(`/api/app/wrong-questions/${wrongQuestionId}/mastered`)
}

export function saveFavorite(payload: { question_id: number; note?: string }) {
  return apiPost('/api/app/favorites', payload)
}
