import express from 'express';
import fs from 'fs';
import path from 'path';
import { Router } from 'express';

const router = Router();

function getFrontendDist() {
  return path.join(process.cwd(), 'frontend', 'dist');
}

function injectConfig(html: string, guildId: string) {
  const baseRoot = process.env.WEB_BASE_PATH || '/ucp';
  const config = {
    baseRoot,
    baseDashboard: `${baseRoot}/dashboard`,
    baseApi: `${baseRoot}/api`,
    baseAuth: `${baseRoot}/auth`,
    initialGuildId: guildId
  };

  return html.replace(
    '__PAPO_CONFIG__',
    `window.__PAPO__ = ${JSON.stringify(config)};`
  );
}

router.use('/assets', (req, res, next) => {
  const assetPath = path.join(getFrontendDist(), 'assets');
  if (!fs.existsSync(assetPath)) {
    return next();
  }

  return express.static(assetPath)(req, res, next);
});

router.get('/', (req, res) => {
  if (!req.session?.user) {
    const baseRoot = process.env.WEB_BASE_PATH || '/ucp';
    return res.redirect(`${baseRoot}/auth/discord`);
  }

  const requestPath = req.originalUrl.split('?')[0] || '';
  if (!requestPath.endsWith('/')) {
    const query = req.originalUrl.includes('?') ? `?${req.originalUrl.split('?')[1]}` : '';
    return res.redirect(`${requestPath}/${query}`);
  }

  const guildId = typeof req.query.guildId === 'string' ? req.query.guildId : '';
  const distDir = getFrontendDist();
  const indexPath = path.join(distDir, 'index.html');

  if (!fs.existsSync(indexPath)) {
    return res.status(503).send(`
      <!doctype html>
      <html lang="de">
        <head>
          <meta charset="UTF-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          <title>Papo Dashboard</title>
          <style>
            body {
              margin: 0;
              min-height: 100vh;
              display: grid;
              place-items: center;
              background: linear-gradient(180deg, #0b0f17 0%, #070910 100%);
              color: #f8fafc;
              font-family: Inter, system-ui, sans-serif;
            }
            .shell {
              width: min(640px, calc(100% - 32px));
              padding: 28px;
              border-radius: 20px;
              background: rgba(17, 24, 39, 0.9);
              border: 1px solid rgba(255,255,255,0.08);
              box-shadow: 0 28px 64px rgba(0,0,0,0.35);
            }
            h1 { margin: 0 0 10px; font-size: 28px; }
            p { margin: 0; color: rgba(255,255,255,0.65); line-height: 1.6; }
            code { color: #fdba74; }
          </style>
        </head>
        <body>
          <div class="shell">
            <h1>Dashboard-Frontend fehlt</h1>
            <p>Baue zuerst das neue HeroUI-Frontend mit <code>npm --prefix frontend install</code> und danach <code>npm --prefix frontend run build</code>.</p>
          </div>
        </body>
      </html>
    `);
  }

  const html = fs.readFileSync(indexPath, 'utf8');
  return res.type('html').send(injectConfig(html, guildId));
});

router.get('/settings', (_req, res) => {
  res.json({ settings: [] });
});

export default router;
