import express from 'express';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { hasAnyUser, createUser } from '../utils/userStore.js';
import { configManager, CONFIG, getPluginsToConfigure } from '../utils/config.js';

const router = express.Router();

router.get('/', (req, res) => {
    if (hasAnyUser()) {
        return res.redirect('/login');
    }
    const pluginsToConfigure = getPluginsToConfigure();
    res.render('setup', { error: null, pluginsToConfigure });
});

router.post('/', (req, res) => {
    if (hasAnyUser()) {
        return res.redirect('/login');
    }

    const { username, password, confirmPassword, config } = req.body;

    if (!username || !password) {
        return res.render('setup', { error: "Tous les champs sont requis.", pluginsToConfigure: getPluginsToConfigure() });
    }

    if (password !== confirmPassword) {
        return res.render('setup', { error: "Les mots de passe ne correspondent pas.", pluginsToConfigure: getPluginsToConfigure() });
    }

    try {
        if (config) {
            for (const [key, value] of Object.entries(config)) {
                if (value && typeof value === 'string' && value.trim() !== '') {
                    configManager.set(key, value.trim());
                }
            }
            configManager.save();
        }

        const { user } = createUser(username, password, 'admin');

        req.session.regenerate((err) => {
            if (err) {
                console.error('[Setup] Erreur session.regenerate:', err);
                return res.render('setup', { error: "Erreur interne. Réessayez.", pluginsToConfigure: getPluginsToConfigure() });
            }

            (req.session as any).user = {
                id: user.id,
                username: user.username,
                role: user.role,
                loginAt: new Date().toISOString(),
            };

            console.log(`[Setup] Premier admin créé: ${user.username}`);
            res.redirect('/');
        });
    } catch (error: any) {
        console.error('[Setup] Erreur création admin:', error.message);
        res.render('setup', { error: error.message, pluginsToConfigure: getPluginsToConfigure() });
    }
});

export default router;
