import tournamentService from '../services/tournamentService.js';
import HttpError from '../exceptions/HttpError.js';

export const getStages = async (req, res) => {
    const { authcode: token } = req.headers;
    const { clubId, tournamentId } = req.query;
    try {
        if (clubId == null || tournamentId == null) {
            return res.status(400).json({ error: 'clubId und tournamentId sind erforderlich.' });
        }
        const data = await tournamentService.getTournamentStages(token, Number(clubId), Number(tournamentId));
        res.status(200).json(data);
    } catch (error) {
        console.error(error);
        if (error instanceof HttpError) {
            // Debug-Hilfe: zeigt, welche IDs tatsächlich am Endpoint ankamen (ohne sensible Daten)
            res.set('x-debug-stages-clubid', String(clubId));
            res.set('x-debug-stages-tournamentid', String(tournamentId));
            res.set('x-debug-stages-clubid-num', String(Number(clubId)));
            return res.status(error.statusCode || 500).json({ error: error.message });
        }
        res.status(500).json({ error: error.message });
    }
};

export const upsertStages = async (req, res) => {
    const { authcode: token } = req.headers;
    const { clubId, tournamentId, stages, advancement, advancements } = req.body;
    try {
        const data = await tournamentService.upsertTournamentStages(
            token,
            Number(clubId),
            Number(tournamentId),
            stages,
            advancement,
            advancements
        );
        res.status(200).json(data);
    } catch (error) {
        console.error(error);
        if (error instanceof HttpError) {
            res.set('x-debug-stages-clubid', String(clubId));
            res.set('x-debug-stages-tournamentid', String(tournamentId));
            res.set('x-debug-stages-clubid-num', String(Number(clubId)));
            return res.status(error.statusCode || 500).json({ error: error.message });
        }
        res.status(500).json({ error: error.message });
    }
};

export const advanceStage = async (req, res) => {
    const { authcode: token } = req.headers;
    const { clubId, tournamentId, fromStageIndex, toStageIndex } = req.body;
    try {
        const data = await tournamentService.advanceTournamentStage(
            token,
            Number(clubId),
            Number(tournamentId),
            Number(fromStageIndex || 1),
            (toStageIndex == null ? null : Number(toStageIndex))
        );
        res.status(200).json(data);
    } catch (error) {
        console.error(error);
        if (error instanceof HttpError) {
            return res.status(error.statusCode || 500).json({ error: error.message });
        }
        res.status(500).json({ error: error.message });
    }
};
