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';

if (process.env.NODE_ENV === 'production') {
    sharp.cache(false);
}

import { Users } from './src/payload/collections/Users';
import { Media } from './src/payload/collections/Media';
import { FormSubmissions } from './src/payload/collections/FormSubmissions';

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

export default buildConfig({
    admin: {
        user: Users.slug,
        importMap: {
            baseDir: path.resolve(dirname),
        },
        meta: {
            titleSuffix: ' – Cable Creations',
            icons: [{ rel: 'icon', type: 'image/x-icon', url: '/favicon.ico' }],
        },
    },
    collections: [Users, Media, FormSubmissions],
    editor: lexicalEditor({}),
    secret: process.env.PAYLOAD_SECRET || 'fallback-secret-for-dev',
    typescript: {
        outputFile: path.resolve(dirname, 'payload-types.ts'),
    },
    db: postgresAdapter({
        pool: {
            connectionString:
                process.env.DATABASE_URI ||
                process.env.POSTGRES_URI ||
                `postgresql://${process.env.PAYLOAD_DB_USER || 'payload'}:${process.env.PAYLOAD_DB_PASSWORD || 'payload'}@127.0.0.1:5432/${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() || 'Cable Creations',
            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: [],
});
