const express = require('express');
const cors = require('cors');
// Security middleware (using mocks if packages are missing)
let helmet, rateLimit;
try {
  helmet = require('helmet');
} catch (e) {
  helmet = require('./mocks/helmet');
}

try {
  const rl = require('express-rate-limit');
  rateLimit = rl.rateLimit;
} catch (e) {
  const rl = require('./mocks/express-rate-limit');
  rateLimit = rl.rateLimit;
}

const path = require('path');
const db = require('./db'); // Ensure DB is initialized

const app = express();
const PORT = process.env.PORT || 3001;
const HOST = process.env.HOST || '127.0.0.1';
app.disable('etag');

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 100
});

// app.use(helmet());
// app.use(limiter);

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

// Prevent stale cached frontend assets causing old UI logic to persist.
app.use((req, res, next) => {
  res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
  res.setHeader('Pragma', 'no-cache');
  res.setHeader('Expires', '0');
  next();
});

// Rate limiting for login - Disabled for local dev
const loginLimiter = (req, res, next) => next();

// Health check
app.get('/api/health', (req, res) => res.json({ status: 'ok', time: new Date().toISOString() }));

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

// Routes
app.get('/admin', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'admin.html'));
});
app.get('/admin/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'admin.html'));
});

app.use('/api/auth', loginLimiter, require('./routes/auth'));
app.use('/api/articles', require('./routes/articles'));
app.use('/api/categories', require('./routes/categories'));
app.use('/api/ads', require('./routes/ads'));
app.use('/api/pages', require('./routes/pages'));
app.use('/api/menus', require('./routes/menus'));
app.use('/api/site', require('./routes/site'));
app.use('/api/authors', require('./routes/authors'));
app.use('/api/admin', require('./routes/admin'));

// SPA - Redirect all to index.html for pushState if needed, but we use hash routing
app.use((req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

const server = app.listen(PORT, () => {
  console.log(`ސާވަރ ޗަލުވަނީ: http://localhost:${PORT}`);
});

server.on('error', (err) => {
  console.error('ސާވަރ ފެށުމުގައި މައްސަލަ:', err);
});

module.exports = app;
