import express from 'express';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createDbPool, initSchema, isDatabaseConfigured } from './db.mjs';
import { attachPlazaPublicRoutes } from './plaza-public.mjs';

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

function loadEnvFile(filePath) {
  if (!fs.existsSync(filePath)) return;
  for (const line of fs.readFileSync(filePath, 'utf8').split('\n')) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith('#')) continue;
    const eq = trimmed.indexOf('=');
    if (eq < 0) continue;
    const key = trimmed.slice(0, eq).trim();
    const value = trimmed.slice(eq + 1).trim();
    if (!process.env[key]) process.env[key] = value;
  }
}

loadEnvFile(path.join(__dirname, '../../.env.local'));
loadEnvFile(path.join(__dirname, '.env'));

const PORT = Number(process.env.PLAZA_PORT ?? 3001);
const PORTAL_PORT = Number(process.env.H5_PORT ?? 8081);
const PORTAL_BASE = String(process.env.PLAZA_PORTAL_BASE ?? `http://127.0.0.1:${PORTAL_PORT}`).replace(
  /\/$/,
  '',
);
const devPreview = String(process.env.PLAZA_DEV_PREVIEW ?? 'true').toLowerCase() !== 'false';

const app = express();
app.set('trust proxy', 1);

let pool = null;
if (isDatabaseConfigured()) {
  pool = createDbPool();
  await initSchema(pool);
}

attachPlazaPublicRoutes(app, {
  pool,
  portalBase: PORTAL_BASE,
  devPreview,
});

app.get('/health', (_req, res) => {
  res.json({ ok: true, service: 'plaza-public', port: PORT });
});

app.listen(PORT, '127.0.0.1', () => {
  console.log(`Plaza public @ http://127.0.0.1:${PORT}`);
  console.log(`Portal base -> ${PORTAL_BASE}`);
  console.log(`Dev preview  -> ${devPreview ? 'enabled (pending_review visible)' : 'disabled'}`);
});
