const express = require('express');
const path = require('path');
const cors = require('cors');
const { initDatabase } = require('./config/database');

const organizacionRoutes = require('./routes/organizacion');
const encuestasRoutes = require('./routes/encuestas');

initDatabase();

const app = express();
const PORT = process.env.PORT || 4100;

app.use(cors());
app.use(express.json());

app.get('/api/health', (_req, res) => {
  res.json({ success: true, data: { status: 'ok', app: 'encuestas-satisfaccion' } });
});

app.use('/api/organizacion', organizacionRoutes);
app.use('/api/encuestas', encuestasRoutes);

const frontendDist = path.join(__dirname, 'frontend', 'dist');
app.use(express.static(frontendDist));
app.get('*', (req, res, next) => {
  if (req.path.startsWith('/api')) return next();
  const indexPath = path.join(frontendDist, 'index.html');
  res.sendFile(indexPath, (err) => {
    if (err) next();
  });
});

app.listen(PORT, () => {
  console.log(`Encuestas Satisfacción API → http://localhost:${PORT}`);
  console.log(`Frontend dev     → http://localhost:5174 (npm run dev:frontend)`);
});
