import { postgresAdapter } from '@payloadcms/db-postgres'
import { nodemailerAdapter } from '@payloadcms/email-nodemailer'
import { ar } from '@payloadcms/translations/languages/ar'
import { en } from '@payloadcms/translations/languages/en'
import path from 'path'
import { buildConfig } from 'payload'
import sharp from 'sharp'
import { fileURLToPath } from 'url'

import { Courses } from './collections/Courses'
import { Leads } from './collections/Leads'
import { Media } from './collections/Media'
import { Users } from './collections/Users'
import { About, Catalogue, Contact, Home, Pricing, Settings } from './globals'
import { smtpFromEnv } from './lib/mail'
import { migrations } from './migrations'
import { seedIfEmpty } from './seed'

const dirname = path.dirname(fileURLToPath(import.meta.url))
const smtp = smtpFromEnv()

export default buildConfig({
  serverURL: process.env.SITE_URL || '',
  admin: {
    user: Users.slug,
    importMap: { baseDir: path.resolve(dirname) },
    components: { graphics: { Logo: '/components/admin/Brand#Logo', Icon: '/components/admin/Brand#Icon' } },
    meta: { titleSuffix: ' · Thinkera', icons: [{ rel: 'icon', type: 'image/svg+xml', url: '/brand/favicon.svg' }] },
  },
  // the admin speaks Arabic first; each editor can switch to English from their account
  i18n: { supportedLanguages: { ar, en }, fallbackLanguage: 'ar' },
  localization: {
    locales: [
      { code: 'ar', label: 'العربية', rtl: true },
      { code: 'en', label: 'English' },
    ],
    defaultLocale: 'ar',
    fallback: true,
  },
  // with no SMTP_HOST the messages go to the log instead of the network, which is what a local copy wants
  email: smtp ? nodemailerAdapter(smtp) : undefined,
  collections: [Courses, Leads, Media, Users],
  globals: [Home, Catalogue, Pricing, About, Contact, Settings],
  secret: process.env.PAYLOAD_SECRET || '',
  typescript: { outputFile: path.resolve(dirname, 'payload-types.ts') },
  db: postgresAdapter({
    pool: { connectionString: process.env.DATABASE_URL || '' },
    // production applies the migrations in src/migrations when the server starts
    prodMigrations: migrations,
  }),
  sharp,
  onInit: async (payload) => {
    await seedIfEmpty(payload)
  },
})
