import type { CollectionAfterChangeHook, CollectionAfterDeleteHook } from 'payload'
import { cache } from '@/lib/redis'

// Nach dem Speichern/Ändern Cache invalidieren
export const invalidateCacheOnChange: CollectionAfterChangeHook = async ({
  collection,
  doc,
  operation,
}) => {
  const collectionSlug = collection.slug
  
  console.log(`[Cache Invalidation] ${operation} on ${collectionSlug}`)

  // Pattern-basierte Invalidierung
  switch (collectionSlug) {
    case 'pages':
      await cache.delPattern('page:*')
      await cache.delPattern('pages:*')
      break
    case 'posts':
      await cache.delPattern('post:*')
      await cache.delPattern('posts:*')
      break
    case 'social-links':
      await cache.delPattern('nav:*')
      break
    case 'categories':
      await cache.delPattern('categories:*')
      break
    default:
      // Fallback: Collection-spezifisches Pattern
      await cache.delPattern(`${collectionSlug}:*`)
  }

  return doc
}

// Nach dem Löschen Cache invalidieren
export const invalidateCacheOnDelete: CollectionAfterDeleteHook = async ({
  collection,
  doc,
}) => {
  const collectionSlug = collection.slug
  
  console.log(`[Cache Invalidation] delete on ${collectionSlug}`)
  
  await cache.delPattern(`${collectionSlug}:*`)

  return doc
}
