import fs from 'node:fs'
import path from 'node:path'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

const ADMIN_DOMAIN = process.env.VITE_ADMIN_DOMAIN ?? 'meshkee.app'

const certDir = path.resolve(__dirname, '.certs')
const certFile = path.join(certDir, `${ADMIN_DOMAIN}.pem`)
const keyFile = path.join(certDir, `${ADMIN_DOMAIN}-key.pem`)

function getHttpsConfig() {
  if (!fs.existsSync(certFile) || !fs.existsSync(keyFile)) {
    console.warn(
      `[vite] Missing mkcert files in .certs/. Run:\n` +
        `  mkcert -install\n` +
        `  mkcert -cert-file .certs/${ADMIN_DOMAIN}.pem -key-file .certs/${ADMIN_DOMAIN}-key.pem ${ADMIN_DOMAIN}`,
    )
    return undefined
  }

  return {
    key: fs.readFileSync(keyFile),
    cert: fs.readFileSync(certFile),
  }
}

const https = getHttpsConfig()

export default defineConfig({
  plugins: [react()],
  resolve: {
    dedupe: ['react', 'react-dom', 'react-router-dom'],
  },
  server: {
    host: true,
    port: 5174,
    https,
    fs: {
      allow: ['..', '../..'],
    },
    allowedHosts: [ADMIN_DOMAIN, 'localhost', '127.0.0.1'],
  },
  preview: {
    host: true,
    port: 5174,
    https,
    allowedHosts: [ADMIN_DOMAIN, 'localhost', '127.0.0.1'],
  },
})
