import express from 'express';
import morgan from 'morgan';
import path from 'path';
import { fileURLToPath } from 'url';
import { readFileSync } from 'fs';
import apiRouter from './routes/api.js';
import radiusRouter from './routes/radius.js';
import authRouter from './routes/auth.js';

export function createApp() {
  const app = express();
  app.use(express.json());
  app.use(morgan('dev'));

  const __filename = fileURLToPath(import.meta.url);
  const __dirname = path.dirname(__filename);
  app.use(express.static(path.join(__dirname, '..', 'public')));

  // RADIUS hooks (rlm_rest)
  app.use('/', radiusRouter);

  // REST API
  app.use('/api', apiRouter);

  // Auth API
  app.use('/api/auth', authRouter);

  // Simple health endpoint for reverse proxies / checks
  app.get('/healthz', (_req, res) => res.json({ ok: true }));

  // Servir index.html con información de usuario inyectada
  app.get('/', (req, res) => {
    const indexPath = path.join(__dirname, '..', 'public', 'index.html');
    let html = readFileSync(indexPath, 'utf-8');

    // Leer headers de Authentik
    const username = req.headers['x-authentik-username'];
    const email = req.headers['x-authentik-email'];
    const name = req.headers['x-authentik-name'];
    const groups = req.headers['x-authentik-groups'];
    const uid = req.headers['x-authentik-uid'];

    // Crear objeto de usuario
    const userData = username ? {
      authenticated: true,
      user: {
        username,
        email,
        name,
        groups: groups ? groups.split('|').filter(g => g.trim()) : [],
        uid
      }
    } : {
      authenticated: false,
      user: null
    };

    // Inyectar en el HTML antes de </head>
    const injection = `
    <script>
      window.__AUTHENTIK_USER__ = ${JSON.stringify(userData)};
    </script>
  </head>`;

    html = html.replace('</head>', injection);

    res.setHeader('Content-Type', 'text/html');
    res.send(html);
  });

  return app;
}
