import type { CollectionConfig } from 'payload'

import {
  FixedToolbarFeature,
  InlineToolbarFeature,
  lexicalEditor,
} from '@payloadcms/richtext-lexical'
import path from 'path'
import { fileURLToPath } from 'url'

import { adminOnly, adminOrEditor, anyRole, anyRoleAdmin } from '../access/roles'
import { logCollectionChange, logCollectionDelete } from '@/hooks/auditLog'
// import { gcsStorage } from '@payloadcms/storage-gcs'

const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)

export const Media: CollectionConfig = {
  slug: 'media',
  folders: true,
  access: {
    admin: anyRoleAdmin,
    create: adminOrEditor,
    delete: adminOnly,
    read: anyRole,
    update: adminOrEditor,
  },
  fields: [
    {
      name: 'alt',
      type: 'text',
      admin: {
        description: 'Required for accessibility and SEO.',
      },
      hooks: {
        beforeChange: [
          ({ value }) => {
            if (!value || !String(value).trim()) {
              throw new Error('Alt text is required.')
            }
            return value
          },
        ],
      },
    },
    {
      name: 'caption',
      type: 'richText',
      editor: lexicalEditor({
        features: ({ rootFeatures }) => {
          return [...rootFeatures, FixedToolbarFeature(), InlineToolbarFeature()]
        },
      }),
    },
  ],
  upload: {
    adminThumbnail: 'thumbnail',
    focalPoint: true,
    imageSizes: [
      {
        name: 'thumbnail',
        width: 300,
      },
      {
        name: 'square',
        width: 500,
        height: 500,
      },
      {
        name: 'small',
        width: 600,
      },
      {
        name: 'medium',
        width: 900,
      },
      {
        name: 'large',
        width: 1400,
      },
      {
        name: 'xlarge',
        width: 1920,
      },
      {
        name: 'og',
        width: 1200,
        height: 630,
        crop: 'center',
      },
    ],
  },
  hooks: {
    afterChange: [logCollectionChange('media')],
    afterDelete: [logCollectionDelete('media')],
  },
}
