import express from 'express';
import cors from 'cors';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { PORT } from './config.js';
import playerInfo from './routes/playerInfo.js';
import users from './routes/users.js';
import orders from './routes/orders.js';
import packages from './routes/packages.js';
import adminRoutes from './routes/admin.js';
import creatorsRoutes from './routes/creators.js';
import authRoutes from './routes/auth.js';
import { initAutoBackup } from './services/backupManager.js';

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

// Resuelve la carpeta del frontend compilado de forma robusta: funciona en dev
// local (../dist) y en cualquier layout de deploy (./frontend, ../frontend, ./dist).
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const candidates = [
  path.join(__dirname, 'frontend'),
  path.join(__dirname, '..', 'frontend'),
  path.join(__dirname, 'dist'),
  path.join(__dirname, '..', 'dist'),
];
const frontendPath = candidates.find(p => fs.existsSync(path.join(p, 'index.html'))) || candidates[0];
console.log(`[frontend] sirviendo desde: ${frontendPath}`);

// Fase 10: Caché, servidor y despliegue (Immutable assets)
app.use('/assets', express.static(path.join(frontendPath, 'assets'), { immutable: true, maxAge: '1y' }));
// Los archivos estáticos en public (favicon, robots, etc) con validación obligatoria
app.use(express.static(frontendPath, { maxAge: '1h', setHeaders: (res, filePath) => {
  if (filePath.endsWith('index.html')) {
    res.setHeader('Cache-Control', 'no-cache');
  }
}}));

// API
app.use(playerInfo, users, orders, packages, creatorsRoutes, authRoutes, adminRoutes);

// Fallback SPA: cualquier GET que no sea /api ni un archivo estático
// devuelve index.html para que funcione el routing de React (/dashboard, /admin).
app.use((req, res, next) => {
  if (req.method !== 'GET' || req.path.startsWith('/api')) return next();
  res.sendFile(path.join(frontendPath, 'index.html'));
});

app.listen(PORT, '0.0.0.0', () => {
  console.log(`Server running on port ${PORT}`);
  initAutoBackup();
});
