import { api } from './client'
import { createCachedGetter } from './cache'

const FEEDBACK_STATS_TTL_MS = 10_000

const feedbackStatsGetter = createCachedGetter(async () => {
  const { data } = await api.get('/feedbacks', { params: { limit: 1, offset: 0 } })
  return data?.stats
}, FEEDBACK_STATS_TTL_MS)

export async function fetchFeedbacks(status = '') {
  const { data } = await api.get('/feedbacks', { params: status ? { status } : {} })
  return data
}

export async function fetchFeedbackStats(options = {}) {
  return feedbackStatsGetter.run(options)
}

export function clearFeedbackStatsCache() {
  feedbackStatsGetter.clear()
}

export async function replyFeedback(feedbackId, reply) {
  const { data } = await api.post(`/feedbacks/${feedbackId}/reply`, { reply })
  clearFeedbackStatsCache()
  return data
}

export async function closeFeedback(feedbackId) {
  const { data } = await api.post(`/feedbacks/${feedbackId}/close`)
  clearFeedbackStatsCache()
  return data
}

export async function deleteFeedback(feedbackId) {
  const { data } = await api.delete(`/feedbacks/${feedbackId}`)
  clearFeedbackStatsCache()
  return data
}
