import { buildConfig } from 'payload';
import { postgresAdapter } from '@payloadcms/db-postgres';
import { lexicalEditor } from '@payloadcms/richtext-lexical';
import sharp from 'sharp';
import path from 'path';
import { fileURLToPath } from 'url';
import { nodemailerAdapter } from '@payloadcms/email-nodemailer';
import { BlocksFeature } from '@payloadcms/richtext-lexical';
import { payloadBlocks } from './src/payload/blocks/allBlocks';
import { migrations } from './src/migrations';

// Only disable sharp cache in production to prevent memory leaks.
// In dev, the cache avoids 41s+ re-processing per image through VirtioFS.
if (process.env.NODE_ENV === 'production') {
  sharp.cache(false);
}

import { Users } from './src/payload/collections/Users';
import { Media } from './src/payload/collections/Media';
import { Posts } from './src/payload/collections/Posts';
import { FormSubmissions } from './src/payload/collections/FormSubmissions';
import { Products } from './src/payload/collections/Products';
import { Pages } from './src/payload/collections/Pages';
import { seedDatabase } from './src/payload/seed';

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

export default buildConfig({
  onInit: async (payload) => {
    if (process.env.NODE_ENV === 'production') {
      await seedDatabase(payload);
    }
  },
  admin: {
    user: Users.slug,
    importMap: {
      baseDir: path.resolve(dirname),
    },
    components: {
      graphics: {
        Logo: '/src/payload/components/Logo',
        Icon: '/src/payload/components/Icon',
      },
    },
    meta: {
      titleSuffix: ' – KLZ Cables',
      icons: [{ rel: 'icon', type: 'image/x-icon', url: '/favicon.ico' }],
    },
  },
  localization: {
    locales: [
      { label: 'Deutsch', code: 'de' },
      { label: 'English', code: 'en' },
    ],
    defaultLocale: 'de',
    fallback: true,
  },
  collections: [Users, Media, Posts, FormSubmissions, Products, Pages],
  editor: lexicalEditor({
    features: ({ defaultFeatures }) => [
      ...defaultFeatures,
      BlocksFeature({
        blocks: payloadBlocks,
      }),
    ],
  }),
  secret: process.env.PAYLOAD_SECRET || 'fallback-secret-for-dev',
  typescript: {
    outputFile: path.resolve(dirname, 'payload-types.ts'),
  },
  db: postgresAdapter({
    prodMigrations: migrations,
    migrationDir:
      process.env.NODE_ENV === 'production' ? undefined : path.resolve(dirname, 'src/migrations'),
    pool: {
      connectionString:
        process.env.DATABASE_URI ||
        process.env.POSTGRES_URI ||
        `postgresql://${process.env.PAYLOAD_DB_USER || 'payload'}:${process.env.PAYLOAD_DB_PASSWORD || '120in09oenaoinsd9iaidon'}@127.0.0.1:54322/${process.env.PAYLOAD_DB_NAME || 'payload'}`,
    },
  }),
  email: process.env.MAIL_HOST
    ? nodemailerAdapter({
        defaultFromAddress:
          process.env.MAIL_FROM?.replace(/.*<|>.*/g, '') || 'postmaster@mg.mintel.me',
        defaultFromName: process.env.MAIL_FROM?.split('<')[0]?.trim() || 'KLZ Cables',
        transportOptions: {
          host: process.env.MAIL_HOST || 'smtp.eu.mailgun.org',
          port: Number(process.env.MAIL_PORT) || 587,
          ...(process.env.MAIL_USERNAME
            ? {
                auth: {
                  user: process.env.MAIL_USERNAME,
                  pass: process.env.MAIL_PASSWORD,
                },
              }
            : {}),
        },
      })
    : undefined,
  sharp,
  plugins: [],
});
