import type { CollectionConfig } from 'payload';
import { lexicalEditor, BlocksFeature } from '@payloadcms/richtext-lexical';

import { StickyNarrative } from '../blocks/StickyNarrative';
import { ComparisonGrid } from '../blocks/ComparisonGrid';
import { VisualLinkPreview } from '../blocks/VisualLinkPreview';
import { TechnicalGrid } from '../blocks/TechnicalGrid';
import { HighlightBox } from '../blocks/HighlightBox';
import { AnimatedImage } from '../blocks/AnimatedImage';
import { ChatBubble } from '../blocks/ChatBubble';
import { PowerCTA } from '../blocks/PowerCTA';
import { Callout } from '../blocks/Callout';
import { Stats } from '../blocks/Stats';
import { SplitHeading } from '../blocks/SplitHeading';
import { ProductTabs } from '../blocks/ProductTabs';

export const Products: CollectionConfig = {
  slug: 'products',
  admin: {
    defaultColumns: ['featuredImage', 'title', 'sku', 'updatedAt', '_status'],
  },
  versions: {
    drafts: true,
  },
  access: {
    read: ({ req: { user } }) => {
      if (process.env.NODE_ENV === 'development' || process.env.TARGET === 'staging') {
        return true;
      }
      if (user) {
        return true;
      }
      return {
        _status: {
          equals: 'published',
        },
      };
    },
  },
  hooks: {
    afterChange: [
      async ({ doc, req, operation }) => {
        // Run index sync asynchronously to not block the CMS save operation
        setTimeout(async () => {
          try {
            const { upsertProductVector, deleteProductVector } = await import('../../lib/qdrant');

            // Check if product is published
            if (doc._status !== 'published') {
              await deleteProductVector(doc.id);
              req.payload.logger.info(`Removed drafted product ${doc.sku} from Qdrant`);
            } else {
              // Serialize payload
              const contentText = `${doc.title} - SKU: ${doc.sku}\n${doc.description || ''}`;
              const payload = {
                id: doc.id,
                title: doc.title,
                sku: doc.sku,
                slug: doc.slug,
                description: doc.description,
                featuredImage: doc.featuredImage, // usually just ID or URL depending on depth
              };
              await upsertProductVector(doc.id, contentText, payload);
              req.payload.logger.info(`Upserted product ${doc.sku} to Qdrant`);
            }
          } catch (error) {
            req.payload.logger.error({ msg: 'Error syncing product to Qdrant', err: error, productId: doc.id });
          }
        }, 0);
        return doc;
      },
    ],
    afterDelete: [
      async ({ id, req }) => {
        try {
          const { deleteProductVector } = await import('../../lib/qdrant');
          await deleteProductVector(id as string | number);
          req.payload.logger.info(`Deleted product ${id} from Qdrant`);
        } catch (error) {
          req.payload.logger.error({ msg: 'Error deleting product from Qdrant', err: error, productId: id });
        }
      },
    ],
  },
  fields: [
    {
      name: 'title',
      type: 'text',
      required: true,
      localized: true,
    },
    {
      name: 'sku',
      type: 'text',
      required: true,
      admin: {
        position: 'sidebar',
      },
    },
    {
      // slug is shared: the cable name (e.g. "n2xy") is the same in DE and EN
      name: 'slug',
      type: 'text',
      required: true,
      admin: {
        position: 'sidebar',
      },
    },
    {
      name: 'description',
      type: 'textarea',
      required: true,
      localized: true,
    },
    {
      name: 'categories',
      type: 'array',
      required: true,
      fields: [
        {
          name: 'category',
          type: 'text',
        },
      ],
      admin: {
        position: 'sidebar',
      },
    },
    {
      name: 'featuredImage',
      type: 'upload',
      relationTo: 'media',
      admin: {
        position: 'sidebar',
        description: 'The primary thumbnail used in list views.',
      },
    },
    {
      name: 'images',
      type: 'upload',
      relationTo: 'media',
      hasMany: true,
      admin: {
        position: 'sidebar',
      },
    },
    {
      name: 'application',
      type: 'richText',
      localized: true,
      editor: lexicalEditor({}),
    },
    {
      name: 'content',
      type: 'richText',
      localized: true,
      editor: lexicalEditor({
        features: ({ defaultFeatures }) => [
          ...defaultFeatures,
          BlocksFeature({
            blocks: [
              StickyNarrative,
              ComparisonGrid,
              VisualLinkPreview,
              TechnicalGrid,
              HighlightBox,
              AnimatedImage,
              ChatBubble,
              PowerCTA,
              Callout,
              Stats,
              SplitHeading,
              ProductTabs,
            ],
          }),
        ],
      }),
    },
  ],
};
