const express = require('express');
const cors = require('cors');
const path = require('path');

const app = express();

app.use(cors());

// --- Simple in-memory metrics (reset when the process restarts) ---------
let requestCount = 0;
let lastResponseTime = 0;

app.use((req, res, next) => {
  requestCount++;
  const start = Date.now();
  res.on('finish', () => {
    lastResponseTime = Date.now() - start;
  });
  next();
});

// Serve the dashboard (public/index.html) at the root, plus any static assets
app.use(express.static(path.join(__dirname, 'public')));

// --- Health check used by the monitor script and by ghaymah's platform --
app.get('/health', (req, res) => {
  res.json({
    status: 'Online',
    uptime_seconds: Math.round(process.uptime()),
    request_count: requestCount,
    response_time_ms: lastResponseTime,
    timestamp: new Date().toISOString(),
  });
});

// Plain-text info route, separate from the dashboard which now owns '/'
app.get('/api', (req, res) => {
  res.send('Welcome to the Backend API! Health check available at /health');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, '0.0.0.0', () => {
  console.log(`API is running on port ${PORT}`);
});