// src/app.js
const express = require('express');

const config = require('./config');
const db = require('./db/knex');
const mqttClient = require('./mqtt');

const usersRouter = require('./routes/users.routes');
const chargersRouter = require('./routes/chargers.routes');
const sessionsRouter = require('./routes/sessions.routes');
const pushRouter = require('./routes/push.routes');

const errorHandler = require('./middleware/errorHandler');

const app = express();

app.disable('x-powered-by');

// ✅ atrás de reverse proxy em produção (nginx/traefik/etc.)
if (config.env === 'production') {
  app.set('trust proxy', 1);
}

// body parser
app.use(express.json({ limit: '1mb' }));

// CORS simples sem dependência extra
app.use((req, res, next) => {
  const origin = req.headers.origin;
  if (origin && config.corsOrigins.includes(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
    res.setHeader('Vary', 'Origin');
    res.setHeader('Access-Control-Allow-Credentials', 'true');
  }

  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');

  if (req.method === 'OPTIONS') return res.sendStatus(204);
  next();
});

// liveness
app.get('/health', (req, res) => res.json({ ok: true }));

// readiness: DB + MQTT
app.get('/ready', async (req, res) => {
  try {
    await db.raw('select 1 as ok');
    const mqttOk = typeof mqttClient?.isConnected === 'function' ? mqttClient.isConnected() : false;

    if (!mqttOk) {
      return res.status(503).json({ ok: false, db: true, mqtt: false });
    }

    return res.json({ ok: true, db: true, mqtt: true });
  } catch (err) {
    return res.status(503).json({ ok: false, db: false, mqtt: false });
  }
});

// routes
app.use('/api/users', usersRouter);
app.use('/api/chargers', chargersRouter);
app.use('/api/charger_sessions', sessionsRouter);
app.use('/api/push', pushRouter);

// 404
app.use((req, res) => {
  res.status(404).json({ success: false, message: 'Not found' });
});

// error handler
app.use(errorHandler);

module.exports = app;
