import type { CollectionAfterChangeHook, CollectionAfterDeleteHook } from 'payload'

import { revalidatePath, revalidateTag } from 'next/cache'

export const revalidateStory: CollectionAfterChangeHook = ({
  doc,
  previousDoc,
  req: { payload, context },
}) => {
  if (!context.disableRevalidate) {
    if (doc._status === 'published') {
      const path = `/truyen/${doc.slug}`
      payload.logger.info(`Revalidating story at path: ${path}`)
      revalidatePath(path)
      revalidateTag('stories-sitemap', 'max')
    }

    if (previousDoc?._status === 'published' && doc._status !== 'published') {
      const oldPath = `/truyen/${previousDoc.slug}`
      payload.logger.info(`Revalidating old story at path: ${oldPath}`)
      revalidatePath(oldPath)
      revalidateTag('stories-sitemap', 'max')
    }
  }
  return doc
}

export const revalidateDelete: CollectionAfterDeleteHook = ({ doc, req: { context } }) => {
  if (!context.disableRevalidate) {
    revalidatePath(`/truyen/${doc?.slug}`)
    revalidateTag('stories-sitemap', 'max')
  }
  return doc
}
