// Load .env file if present (optional)
try { require('dotenv').config(); } catch { /* dotenv not installed – use env vars directly */ }

const express = require('express');
const session = require('express-session');
const cors    = require('cors');
const path    = require('path');

const log             = require('./src/logger');
const { initDB }      = require('./src/db');
const { startPoller } = require('./src/poller');
const apiRoutes       = require('./src/routes/api');

const app  = express();
const PORT = parseInt(process.env.PORT || '3000', 10);

// ── Middleware ────────────────────────────────────────────────────────────────

app.use(cors({ origin: true, credentials: true }));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use(session({
  secret:            process.env.SESSION_SECRET || 'sms-gateway-change-this-secret',
  resave:            false,
  saveUninitialized: false,
  cookie: {
    secure:   false,
    httpOnly: true,
    maxAge:   24 * 60 * 60 * 1000,
  },
}));

// HTTP request logging (DEBUG level)
app.use((req, res, next) => {
  const start = Date.now();
  res.on('finish', () => {
    const ms = Date.now() - start;
    log.debug('HTTP', `${req.method} ${req.originalUrl} → ${res.statusCode} (${ms}ms)`);
  });
  next();
});

// ── Static files ──────────────────────────────────────────────────────────────

app.use(express.static(path.join(__dirname, 'public')));

// ── Routes ────────────────────────────────────────────────────────────────────

app.use('/api', apiRoutes);

// SPA fallback – serve index.html for any non-API route
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// ── Startup ───────────────────────────────────────────────────────────────────

async function start() {
  initDB();
  startPoller();

  app.listen(PORT, () => {
    log.info('Server', `SMS Gateway running at http://localhost:${PORT}`);
    log.info('Server', 'Default admin: admin / changeme  (change via Settings)');
    log.info('Server', `Log level: ${log.getLevel()}  (set LOG_LEVEL env or PUT /api/log-level)`);
  });
}

start().catch(err => {
  log.error('Server', 'Fatal startup error:', err.message);
  process.exit(1);
});
