#!/usr/bin/env node
/**
 * DBAOps Enterprise™ Dashboard REST API
 * Cross-platform Node.js - runs on Windows, Linux, Mac
 * Serves /api/dashboard, /api/summary, /api/alerts, /api/servers
 * Reads DBAOps.config.json for connection; falls back to data.json
 */

const http = require('http');
const fs = require('fs');
const path = require('path');

const PORT = process.env.DBAOPS_API_PORT || 9002;

// Resolve config path: api/ -> WebDashboard/ -> Application/Config/
const apiDir = __dirname;
const webDashboardDir = path.join(apiDir, '..');
const configPaths = [
  path.join(webDashboardDir, '..', 'Config', 'DBAOps.config.json'),
  path.join(apiDir, 'DBAOps.config.json'),
  path.join(process.cwd(), 'DBAOps.config.json'),
];

let config = {};
for (const p of configPaths) {
  try {
    if (fs.existsSync(p)) {
      config = JSON.parse(fs.readFileSync(p, 'utf8'));
      break;
    }
  } catch (_) {}
}

const dataJsonPath = path.join(webDashboardDir, 'data.json');
const port = config.WebDashboard?.ApiPort || config.ApiPort || PORT;

function loadDataJson() {
  try {
    if (fs.existsSync(dataJsonPath)) {
      return JSON.parse(fs.readFileSync(dataJsonPath, 'utf8'));
    }
  } catch (e) {
    console.error('Error loading data.json:', e.message);
  }
  return null;
}

function corsHeaders() {
  return {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Content-Type': 'application/json',
  };
}

function sendJson(res, statusCode, data) {
  res.writeHead(statusCode, corsHeaders());
  res.end(JSON.stringify(data));
}

const routes = {
  '/api/dashboard': (data) => data,
  '/api/summary': (data) => ({
    summary: data?.summary || {},
    generatedAt: data?.generatedAt,
  }),
  '/api/alerts': (data) => ({
    recentAlerts: data?.recentAlerts || [],
    generatedAt: data?.generatedAt,
  }),
  '/api/servers': (data) => ({
    servers: data?.servers || { all: [] },
    generatedAt: data?.generatedAt,
  }),
  '/api/security': (data) => ({
    securityCompliance: data?.securityCompliance || { checks: [], centralServer: {} },
    generatedAt: data?.generatedAt,
  }),
};

const server = http.createServer((req, res) => {
  if (req.method === 'OPTIONS') {
    res.writeHead(204, corsHeaders());
    res.end();
    return;
  }

  if (req.method !== 'GET') {
    sendJson(res, 405, { error: 'Method not allowed' });
    return;
  }

  const url = req.url.split('?')[0];
  const handler = routes[url];

  if (!handler) {
    if (url === '/api' || url === '/api/') {
      sendJson(res, 200, {
        name: 'DBAOps Dashboard API',
        version: '1.0.0',
        endpoints: ['/api/dashboard', '/api/summary', '/api/alerts', '/api/servers', '/api/security'],
      });
      return;
    }
    sendJson(res, 404, { error: 'Not found', path: url });
    return;
  }

  const data = loadDataJson();
  if (!data) {
    sendJson(res, 503, {
      error: 'Data not available',
      message: 'data.json not found. Run Get-DBAOpsDashboardData.ps1 to generate.',
    });
    return;
  }

  try {
    const result = handler(data);
    sendJson(res, 200, result);
  } catch (e) {
    sendJson(res, 500, { error: 'Internal error', message: e.message });
  }
});

server.listen(port, () => {
  console.log(`DBAOps Dashboard API listening on port ${port}`);
  console.log(`  /api/dashboard - full data`);
  console.log(`  /api/summary   - summary only`);
  console.log(`  /api/alerts    - alerts only`);
  console.log(`  /api/servers   - servers only`);
  console.log(`  /api/security  - gMSA, SA, TDE, TLS, RBAC compliance`);
  console.log(`  data.json path: ${dataJsonPath}`);
});
