import { adminApi } from './client'
import { unwrapItem, unwrapList } from './helpers'
import { normalizePageBlock } from './normalizers'
import type {
  AdminPageBlockRecord,
  ApiItemResponse,
  ApiListResponse,
} from './types'

export type BlockUpsertPayload = {
  type: string
  content: Record<string, unknown>
  order_index?: number
}

export type BlockApi = {
  fetchBlocks: () => Promise<AdminPageBlockRecord[]>
  createBlock: (payload: BlockUpsertPayload) => Promise<AdminPageBlockRecord>
  updateBlock: (
    blockId: number | string,
    payload: BlockUpsertPayload
  ) => Promise<AdminPageBlockRecord>
  deleteBlock: (blockId: number | string) => Promise<void>
  reorderBlocks: (
    items: Array<{ id: number | string; order_index: number }>
  ) => Promise<void>
  queryKey: readonly unknown[]
  parentQueryKey: readonly unknown[]
}

export function createBlockApi(
  basePath: string,
  queryKey: readonly unknown[],
  parentQueryKey: readonly unknown[]
): BlockApi {
  return {
    queryKey,
    parentQueryKey,

    async fetchBlocks() {
      const response = await adminApi.get<
        ApiListResponse<Record<string, unknown>>
      >(basePath)
      return unwrapList(response).map(normalizePageBlock)
    },

    async createBlock(payload: BlockUpsertPayload) {
      const response = await adminApi.post<
        ApiItemResponse<Record<string, unknown>>
      >(basePath, payload)
      return normalizePageBlock(unwrapItem(response))
    },

    async updateBlock(
      blockId: number | string,
      payload: BlockUpsertPayload
    ) {
      const response = await adminApi.put<
        ApiItemResponse<Record<string, unknown>>
      >(`${basePath}/${blockId}`, payload)
      return normalizePageBlock(unwrapItem(response))
    },

    async deleteBlock(blockId: number | string) {
      await adminApi.delete(`${basePath}/${blockId}`)
    },

    async reorderBlocks(
      items: Array<{ id: number | string; order_index: number }>
    ) {
      await adminApi.post(`${basePath}/reorder`, { items })
    },
  }
}

export function pageBlockApi(pageId: number | string): BlockApi {
  return createBlockApi(
    `/pages/${pageId}/blocks`,
    ['pages', pageId, 'blocks'],
    ['pages']
  )
}

export function courseBlockApi(courseId: number | string): BlockApi {
  return createBlockApi(
    `/courses/${courseId}/blocks`,
    ['courses', courseId, 'blocks'],
    ['courses']
  )
}
