import { z } from 'zod'

import { HttpServer } from '~/libs/http-server'
import type { TContentSchema } from '~/pages/contents-create'

const newsResponseSchema = z.object({
  data: z.object({
    Message: z.string(),
  }),
})

type TParameter = {
  accessToken: string
  payload: TContentSchema
}

export const createNewsRequest = async (parameters: TParameter) => {
  const { accessToken, payload } = parameters
  try {
    const { categories, tags, ...restPayload } = payload
    const transformedPayload = {
      ...restPayload,
      categories: categories.map((category) => category?.id),
      tags: tags?.map((tag) => tag?.id),
      live_at: new Date(payload?.live_at).toISOString(),
    }
    if (transformedPayload.tags?.length === 0) {
      delete transformedPayload.tags
    }
    const { data } = await HttpServer({ accessToken }).post(
      '/api/news/create',
      transformedPayload,
    )
    return newsResponseSchema.parse(data)
  } catch (error) {
    // eslint-disable-next-line unicorn/no-useless-promise-resolve-reject
    return Promise.reject(error)
  }
}
