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

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

let requestCount = 0;

app.use((req, res, next) => {
  requestCount += 1;
  const startedAt = process.hrtime.bigint();

  res.setHeader('Access-Control-Allow-Origin', '*');

  res.on('finish', () => {
    const responseTimeMs = Number(process.hrtime.bigint() - startedAt) / 1000000;
    console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${responseTimeMs.toFixed(2)}ms`);
  });

  next();
});

app.get('/', (req, res) => {
  res.json({
    message: 'Ahmed Nasser SRE Assessment API'
  });
});

app.get('/health', (req, res) => {
  res.json({
    status: 'UP',
    uptime: Number(process.uptime().toFixed(2)),
    timestamp: new Date().toISOString()
  });
});

app.get('/metrics', (req, res) => {
  const memoryUsageMB = process.memoryUsage().rss / 1024 / 1024;

  res.json({
    status: 'UP',
    uptime: Number(process.uptime().toFixed(2)),
    requests: requestCount,
    memoryUsageMB: Number(memoryUsageMB.toFixed(2)),
    timestamp: new Date().toISOString()
  });
});

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

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