import type { CollectionAfterChangeHook, CollectionAfterDeleteHook } from 'payload'

import { revalidatePath } from 'next/cache'

export const revalidateChapter: CollectionAfterChangeHook = ({
  doc,
  previousDoc,
  req: { payload, context },
}) => {
  if (!context.disableRevalidate) {
    const storySlug = typeof doc.story === 'object' ? doc.story?.slug : null

    if (storySlug && doc._status === 'published') {
      const path = `/truyen/${storySlug}/${doc.slug}`
      payload.logger.info(`Revalidating chapter at path: ${path}`)
      revalidatePath(path)
      revalidatePath(`/truyen/${storySlug}`)
    }

    if (storySlug && previousDoc?._status === 'published' && doc._status !== 'published') {
      revalidatePath(`/truyen/${storySlug}/${previousDoc.slug}`)
    }
  }
  return doc
}

export const revalidateDelete: CollectionAfterDeleteHook = ({ doc, req: { context } }) => {
  if (!context.disableRevalidate) {
    const storySlug = typeof doc.story === 'object' ? doc.story?.slug : null
    if (storySlug) {
      revalidatePath(`/truyen/${storySlug}/${doc?.slug}`)
      revalidatePath(`/truyen/${storySlug}`)
    }
  }
  return doc
}
