import express from 'express';
import { viewAuthMiddleware, viewRequireAdmin } from '../utils/authMiddleware.js';
import { hasAnyUser } from '../utils/userStore.js';

const router = express.Router();

// ============================================================
//  Setup Gatekeeper — Redirige vers /setup si aucun user n'existe
// ============================================================

const setupGatekeeper = (req: express.Request, res: express.Response, next: express.NextFunction) => {
    // Laisser passer les routes de setup et les assets statiques
    if (req.path === '/setup' || req.path.startsWith('/setup/') ||
        req.path === '/login' || req.path.startsWith('/login') ||
        req.path.startsWith('/images') || req.path.startsWith('/style') ||
        req.path.startsWith('/app.') || req.path.startsWith('/lucide') ||
        req.path.startsWith('/sw.') || req.path.startsWith('/manifest')) {
        return next();
    }

    if (!hasAnyUser()) {
        return res.redirect('/setup');
    }

    next();
};

// Appliquer le gatekeeper à toutes les routes de vue
router.use(setupGatekeeper);

// ============================================================
//  Routes publiques
// ============================================================

router.get('/login', (req, res) => {
    if ((req.session as any).user) {
        const defaultPage = req.cookies?.defaultPage || '/trending';
        const allowedPages = ['/trending', '/recent', '/search', '/downloads', '/manual', '/settings'];
        if (allowedPages.includes(defaultPage)) {
            res.redirect(defaultPage);
        } else {
            res.redirect('/trending');
        }
    } else {
        res.render('login');
    }
});

// ============================================================
//  Routes protégées — Injecter les infos user dans les vues
// ============================================================

const protectedRoute = (viewName: string, page: string) => {
    return [viewAuthMiddleware, (req: express.Request, res: express.Response) => {
        const session = req.session as any;
        res.render(viewName, {
            page,
            currentUser: session.user || null,
        });
    }] as express.RequestHandler[];
};

router.get('/trending', ...protectedRoute('trending', 'trending'));
router.get('/recent', ...protectedRoute('recent', 'recent'));
router.get('/search', ...protectedRoute('search', 'search'));
router.get('/downloads', ...protectedRoute('downloads', 'downloads'));
router.get('/manual', ...protectedRoute('manual', 'manual'));
router.get('/settings', viewAuthMiddleware, viewRequireAdmin, async (req, res) => {
    const session = req.session as any;
    const { getPluginsToConfigure, CONFIG } = await import('../utils/config.js');
    res.render('settings', {
        page: 'settings',
        currentUser: session.user || null,
        pluginsToConfigure: getPluginsToConfigure(),
        preferredHosters: CONFIG.PREFERRED_HOSTERS
    });
});

// Admin endpoint redirects to settings
router.get('/admin', viewAuthMiddleware, (req, res) => {
    res.redirect('/settings');
});

// Home endpoint redirects depending on authentication status
router.get('/', (req, res) => {
    if ((req.session as any).user) {
        const defaultPage = req.cookies?.defaultPage || '/trending';
        const allowedPages = ['/trending', '/recent', '/search', '/downloads', '/manual', '/settings'];
        if (allowedPages.includes(defaultPage)) {
            res.redirect(defaultPage);
        } else {
            res.redirect('/trending');
        }
    } else {
        res.redirect('/login');
    }
});

export default router;
