import { BeforeSync, DocToSync } from '@payloadcms/plugin-search/types'

export const beforeSyncWithSearch: BeforeSync = async ({ req, originalDoc, searchDoc }) => {
  const {
    doc: { relationTo: collection },
  } = searchDoc

  // Handle stories collection
  if (collection === 'stories') {
    const { slug, id, category, title, author } = originalDoc

    const modifiedDoc: DocToSync = {
      ...searchDoc,
      slug,
      meta: {
        title: title,
        description: author ? `Tác giả: ${author}` : '',
        image: null,
      },
      categories: [],
    }

    if (category) {
      const categoryId = typeof category === 'object' ? category.id : category
      const categoryTitle = typeof category === 'object' ? category.title : ''
      modifiedDoc.categories = [
        {
          relationTo: 'categories',
          categoryID: String(categoryId),
          title: categoryTitle,
        },
      ]
    }

    return modifiedDoc
  }

  // Handle posts collection (original logic)
  const { slug, id, categories, title, meta } = originalDoc

  const modifiedDoc: DocToSync = {
    ...searchDoc,
    slug,
    meta: {
      ...meta,
      title: meta?.title || title,
      image: meta?.image?.id || meta?.image,
      description: meta?.description,
    },
    categories: [],
  }

  if (categories && Array.isArray(categories) && categories.length > 0) {
    const populatedCategories: { id: string | number; title: string }[] = []
    for (const category of categories) {
      if (!category) continue

      if (typeof category === 'object') {
        populatedCategories.push(category)
        continue
      }

      const doc = await req.payload.findByID({
        collection: 'categories',
        id: category,
        disableErrors: true,
        depth: 0,
        select: { title: true },
        req,
      })

      if (doc !== null) {
        populatedCategories.push(doc)
      } else {
        console.error(
          `Failed. Category not found when syncing collection '${collection}' with id: '${id}' to search.`,
        )
      }
    }

    modifiedDoc.categories = populatedCategories.map((each) => ({
      relationTo: 'categories',
      categoryID: String(each.id),
      title: each.title,
    }))
  }

  return modifiedDoc
}
