import { adminApi } from './client'
import { unwrapItem } from './helpers'
import { normalizeComment, normalizePaginated } from './normalizers'
import type {
  AdminCommentRecord,
  ApiItemResponse,
  ApiListResponse,
  PaginatedResult,
} from './types'

export type CommentsQuery = {
  page?: number
  perPage?: number
  search?: string
  is_approved?: boolean
}

export type CommentUpdatePayload = {
  is_approved?: boolean
  admin_reply?: string | null
}

export async function fetchComments(
  query: CommentsQuery
): Promise<PaginatedResult<AdminCommentRecord>> {
  const response = await adminApi.get<ApiListResponse<Record<string, unknown>>>(
    '/comments',
    {
      params: {
        page: query.page,
        per_page: query.perPage,
        search: query.search || undefined,
        is_approved: query.is_approved,
      },
    }
  )

  return normalizePaginated(response.data, normalizeComment)
}

export async function fetchComment(commentId: number | string) {
  const response = await adminApi.get<ApiItemResponse<Record<string, unknown>>>(
    `/comments/${commentId}`
  )
  return normalizeComment(unwrapItem(response))
}

export async function updateComment(
  commentId: number | string,
  payload: CommentUpdatePayload
) {
  const response = await adminApi.put<ApiItemResponse<Record<string, unknown>>>(
    `/comments/${commentId}`,
    payload
  )
  return normalizeComment(unwrapItem(response))
}

export async function deleteComment(commentId: number | string) {
  await adminApi.delete(`/comments/${commentId}`)
}
