const express = require('express');
const cors = require('cors');
const session = require('express-session');
const path = require('path');
const db = require('./src/db');
const config = require('./src/config');

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

app.use(cors({
  origin: true,
  credentials: true
}));

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

app.use(session({
  secret: 'peak-platform-secret-key-123',
  resave: false,
  saveUninitialized: false,
  cookie: { secure: process.env.NODE_ENV === 'production', maxAge: 86400000 }
}));

// Route Rewrite for legacy api.php compatibility
app.use((req, res, next) => {
  if (req.path === '/api.php' || req.path === '/api') {
    if (req.query.route) {
      req.url = req.query.route;
    }
  }
  next();
});

// Setup routes
app.use('/auth', require('./src/routes/auth'));
app.use('/settings', require('./src/routes/settings'));
app.use('/profile', require('./src/routes/profile'));
app.use('/activity', require('./src/routes/activity'));
app.use('/workflows', require('./src/routes/workflows'));
app.use('/generate-image', require('./src/routes/image'));
app.use('/generate-video', require('./src/routes/video'));
app.use('/chat', require('./src/routes/chat'));

// Provide settings to HTML files
app.get('*.html', async (req, res, next) => {
  try {
    const filePath = path.join(__dirname, req.path === '/' ? 'index.html' : req.path);
    const fs = require('fs');
    if (fs.existsSync(filePath)) {
      let html = fs.readFileSync(filePath, 'utf8');
      const settingsRows = await db.query("SELECT setting_key, setting_value, setting_type, category FROM settings");
      const settings = {};
      settingsRows.forEach(row => { settings[row.setting_key] = row.setting_value; });
      const script = `<script>window.__SETTINGS=${JSON.stringify(settings)}</script>`;
      html = html.replace('</head>', script + '</head>');
      res.send(html);
    } else {
      next();
    }
  } catch (err) {
    next();
  }
});

// Static files fallback
app.use(express.static(__dirname));

app.listen(PORT, () => {
  console.log(`Peak Platform Node.js Server running on port ${PORT}`);
});
