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

// Load environment variables from .env file if available
[
  path.join(__dirname, '../.env'),
  path.join(__dirname, '../../.env')
].forEach(envPath => {
  try {
    if (fs.existsSync(envPath)) {
      const envLines = fs.readFileSync(envPath, 'utf8').split(/\r?\n/);
      for (const line of envLines) {
        const trimmed = line.trim();
        if (!trimmed || trimmed.startsWith('#')) continue;
        const match = trimmed.match(/^([\w.-]+)\s*=\s*(.*)$/);
        if (match) {
          const key = match[1];
          let value = match[2] || '';
          if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
            value = value.substring(1, value.length - 1);
          }
          if (!process.env[key]) {
            process.env[key] = value.trim();
          }
        }
      }
    }
  } catch (e) {
    console.error('Error loading .env file:', e.message);
  }
});

const express = require('express');
const cors = require('cors');
const routes = require('./routes/superadmin.routes');

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

app.use(cors({ origin: true, credentials: true }));
app.use(express.json({ limit: '2mb' }));

// Health Check
app.get('/api/health', (req, res) => {
  res.json({
    service: 'NextGen LMS SuperAdmin Engine',
    status: 'HEALTHY',
    version: '1.0.0',
    port: PORT,
    timestamp: new Date().toISOString()
  });
});

// SuperAdmin Routes
app.use('/api', routes);

const server = app.listen(PORT, () => {
  console.log(`=======================================================`);
  console.log(`🚀 Standalone SuperAdmin Server running on port ${PORT}`);
  console.log(`   Tenant Management & Termly Licensing Engine`);
  console.log(`   Health Check: http://localhost:${PORT}/api/health`);
  console.log(`=======================================================`);
});

server.on('error', (err) => {
  if (err.code === 'EADDRINUSE') {
    console.error(`\n❌ [ERROR] Port ${PORT} is already in use.`);
    console.error(`   Run 'npx kill-port ${PORT}' or specify SUPERADMIN_PORT=<port>.\n`);
    process.exit(1);
  }
});

const gracefulShutdown = () => {
  server.close(() => {
    process.exit(0);
  });
};

process.on('SIGINT', gracefulShutdown);
process.on('SIGTERM', gracefulShutdown);
process.once('SIGUSR2', () => {
  server.close(() => {
    process.kill(process.pid, 'SIGUSR2');
  });
});

