require('dotenv').config();
const express = require('express');
const path = require('path');
const morgan = require('morgan');
const fs = require('fs');
const expressLayouts = require('express-ejs-layouts');
const pm = require('./services/project-manager');

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

// Auto-shutdown: when client closes the tab, shutdown after timeout
let shutdownTimer = null;
const SHUTDOWN_DELAY = 10000; // 10 seconds — allows page navigation

function resetShutdownTimer() {
  if (shutdownTimer) {
    clearTimeout(shutdownTimer);
    shutdownTimer = null;
  }
}

function scheduleShutdown() {
  resetShutdownTimer();
  shutdownTimer = setTimeout(() => {
    console.log('\n  Dashboard tab closed — shutting down.');
    process.exit(0);
  }, SHUTDOWN_DELAY);
}

// Reset timer on every request (handles page navigation)
app.use((req, res, next) => {
  if (req.path !== '/shutdown') {
    resetShutdownTimer();
  }
  next();
});

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(expressLayouts);
app.set('layout', 'layouts/main');
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(morgan('dev'));

// Client signals it's leaving (tab close / navigation)
app.post('/shutdown', (req, res) => {
  scheduleShutdown();
  res.json({ shutdown: true });
});

// SSE Endpoint for React-like live reload
app.get('/live-reload', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  res.flushHeaders();
  
  // Keep connection open
  const keepAlive = setInterval(() => {
    res.write(': keepalive\n\n');
  }, 30000);

  req.on('close', () => {
    clearInterval(keepAlive);
    res.end();
  });
});

// Serve Allure reports for each registered project
app.use('/allure-report', (req, res, next) => {
  const projectId = req.query.project;
  const project = projectId ? pm.get(projectId) : pm.getAll()[0];
  if (!project) return res.status(404).send('Project not found');

  const allureDir = path.join(project.path, 'allure-report');
  if (!fs.existsSync(allureDir)) {
    return res.status(404).send('Allure report not found. Run: npx allure generate allure-results --clean -o allure-report');
  }
  express.static(allureDir)(req, res, next);
});

app.use('/', require('./routes/index'));
app.use('/projects', require('./routes/projects'));
app.use('/stories', require('./routes/stories'));
app.use('/runs', require('./routes/runs'));
app.use('/review', require('./routes/review'));
app.use('/analytics', require('./routes/analytics'));
app.use('/export', require('./routes/export'));
app.use('/data', require('./routes/test-data'));

app.use((req, res) => { res.status(404).render('error', { message: 'Page not found' }); });

app.listen(PORT, () => {
  console.log(`QA Dashboard running at http://localhost:${PORT}`);
  console.log(`Close the browser tab to stop the server.`);
});
