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

export type AnnouncementsQuery = {
  page?: number
  perPage?: number
  search?: string
  category?: string
  featured?: string
}

export type AnnouncementUpsertPayload = {
  title: string
  slug?: string
  category: string
  excerpt: string
  content: string
  image?: string | null
  is_featured?: boolean
  meta_title?: string | null
  meta_description?: string | null
  published_at?: string | null
}

export async function fetchAnnouncements(
  query: AnnouncementsQuery
): Promise<PaginatedResult<AdminAnnouncementRecord>> {
  const response = await adminApi.get<ApiListResponse<Record<string, unknown>>>(
    '/announcements',
    {
      params: {
        page: query.page,
        per_page: query.perPage,
        search: query.search || undefined,
        category: query.category || undefined,
        featured: query.featured || undefined,
      },
    }
  )

  return normalizePaginated(response.data, normalizeAnnouncement)
}

export async function fetchAnnouncement(announcementId: number | string) {
  const response = await adminApi.get<ApiItemResponse<Record<string, unknown>>>(
    `/announcements/${announcementId}`
  )
  return normalizeAnnouncement(unwrapItem(response))
}

export async function createAnnouncement(payload: AnnouncementUpsertPayload) {
  const response = await adminApi.post<
    ApiItemResponse<Record<string, unknown>>
  >('/announcements', payload)
  return normalizeAnnouncement(unwrapItem(response))
}

export async function updateAnnouncement(
  announcementId: number | string,
  payload: AnnouncementUpsertPayload
) {
  const response = await adminApi.put<ApiItemResponse<Record<string, unknown>>>(
    `/announcements/${announcementId}`,
    payload
  )
  return normalizeAnnouncement(unwrapItem(response))
}

export async function deleteAnnouncement(announcementId: number | string) {
  await adminApi.delete(`/announcements/${announcementId}`)
}
