require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');

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

// Middlewares
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Static files
app.use(express.static(path.join(__dirname, '..', 'public')));
app.use('/uploads', express.static(path.join(__dirname, '..', 'public', 'uploads')));

// API Routes
app.use('/api/auth', require('./routes/auth.routes'));
app.use('/api/tickets', require('./routes/tickets.routes'));
app.use('/api/assets', require('./routes/assets.routes'));
app.use('/api/knowledge', require('./routes/knowledge.routes'));
app.use('/api/dashboard', require('./routes/dashboard.routes'));
app.use('/api/admin', require('./routes/admin.routes'));

// SPA fallback
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '..', 'public', 'index.html'));
});

// Error handler
app.use((err, req, res, next) => {
  console.error('Error:', err.message);
  res.status(500).json({ error: 'Error interno del servidor' });
});

// Start
app.listen(PORT, () => {
  console.log(`\n✅ HelpDesk ITSM v2.0 en http://localhost:${PORT}`);
  console.log(`📧 Email: ${process.env.EMAIL_USER ? '✓ configurado' : '✗ no configurado'}`);
  console.log(`🤖 IA Gemini: ${process.env.GEMINI_API_KEY ? '✓ activada' : '✗ desactivada (funciona sin ella)'}\n`);
});
