import path from 'path'
import { fileURLToPath } from 'url'
import { buildConfig } from 'payload'
import { postgresAdapter } from '@payloadcms/db-postgres'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { stripePlugin } from '@payloadcms/plugin-stripe'
import sharp from 'sharp'

import { Users } from './collections/Users'
import { Media } from './collections/Media'
import { Products } from './collections/Products'
import { HomePage } from './globals/HomePage'

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

const STRIPE_KEY = process.env.STRIPE_SECRET_KEY || ''
const STRIPE_KEY_IS_REAL = /^sk_(test|live)_[A-Za-z0-9]{20,}$/.test(STRIPE_KEY)

export default buildConfig({
  admin: {
    user: Users.slug,
    meta: {
      titleSuffix: ' — REBOURS',
    },
    livePreview: {
      breakpoints: [
        { label: 'Mobile', name: 'mobile', width: 375, height: 667 },
        { label: 'Tablette', name: 'tablet', width: 768, height: 1024 },
        { label: 'Desktop', name: 'desktop', width: 1440, height: 900 },
      ],
    },
  },
  collections: [Users, Media, Products],
  globals: [HomePage],
  editor: lexicalEditor({}),
  secret: process.env.PAYLOAD_SECRET || 'change-me',
  typescript: {
    outputFile: path.resolve(dirname, 'payload-types.ts'),
  },
  db: postgresAdapter({
    pool: {
      connectionString: process.env.DATABASE_URL || '',
    },
    // Auto-sync schema on boot (small single-tenant CMS — no manual migrations)
    push: true,
  }),
  sharp,
  plugins: [
    stripePlugin({
      stripeSecretKey: STRIPE_KEY,
      stripeWebhooksEndpointSecret: process.env.STRIPE_WEBHOOK_SECRET,
      isTestKey: !STRIPE_KEY.startsWith('sk_live_'),
      rest: false,
      sync: STRIPE_KEY_IS_REAL
        ? [
            {
              collection: 'products',
              stripeResourceType: 'products',
              stripeResourceTypeSingular: 'product',
              fields: [
                { fieldPath: 'productDisplayName', stripeProperty: 'name' },
                { fieldPath: 'description', stripeProperty: 'description' },
              ],
            },
          ]
        : [],
    }),
  ],
  cors: '*',
})
