const {
    SlashCommandBuilder,
    EmbedBuilder,
    ActionRowBuilder,
    ButtonBuilder,
    ButtonStyle,
    MessageFlags
} = require('discord.js');
const { mClient } = require('../../..');
require('dotenv').config()

module.exports = {
    data: new SlashCommandBuilder()
        .setName('ezd')
        .setDescription('Zeigt die täglichen Erster/Zweiter/Dritter Ergebnisse'),

    async execute(interaction, client) {
        const db = mClient.db(process.env.M_DB); // adjust if needed
        const coll = db.collection('items_daily_numbers');

        const today = new Date().toLocaleDateString("en-CA", {
            timeZone: "Europe/Berlin"
        });

        let currentDate = today;

        const sessionId = `${interaction.user.id}-${Date.now()}`;

        const buildEmbed = (doc, date) => {
            const p = doc?.positions || {};

            const line = (emoji, label, key) => {
                const v = p[key];
                return `${emoji} **${label}:** ${v ? `<@${v.userId}>` : "—"}`;
            };

            const germanDate = new Date(`${date}T00:00:00`).toLocaleDateString("de-DE", {
                timeZone: "Europe/Berlin",
                day: "2-digit",
                month: "2-digit",
                year: "numeric"
            });

            return new EmbedBuilder()
                .setTitle(`📊 EZD Übersicht – ${germanDate}`)
                .setColor(0x2b2d31)
                .setDescription([
                    line("🥇", "Ersti", "Ersti"),
                    line("🥈", "Zweiti", "Zweiti"),
                    line("🥉", "Dritti", "Dritti")
                ].join("\n"));
        };

        const buildButtons = (date) => {
            return new ActionRowBuilder().addComponents(
                new ButtonBuilder()
                    .setCustomId(`ezd_prev`)
                    .setLabel("⬅️")
                    .setStyle(ButtonStyle.Secondary),
                new ButtonBuilder()
                    .setCustomId(`ezd_next`)
                    .setLabel("➡️")
                    .setStyle(ButtonStyle.Secondary)
            );
        };

        const doc = await coll.findOne({ date: currentDate });

        const msg = await interaction.reply({
            embeds: [buildEmbed(doc, currentDate)],
            components: [buildButtons(currentDate)]
        });

        const collector = msg.createMessageComponentCollector({
            time: 1000 * 60 * 10 // 10 minutes
        });

        collector.on("collect", async (btn) => {
            if (btn.user.id !== interaction.user.id) {
                return btn.reply({
                    content: "❌ Diese Buttons gehören nicht dir.",
                    flags: MessageFlags.Ephemeral
                });
            }

            if (btn.customId === `ezd_prev`) {
                currentDate = shiftDate(currentDate, -1);
            }

            if (btn.customId === `ezd_next`) {
                currentDate = shiftDate(currentDate, 1);
            }

            const newDoc = await coll.findOne({ date: currentDate });

            await btn.update({
                embeds: [buildEmbed(newDoc, currentDate)],
                components: [buildButtons(currentDate)]
            });
        });
    }
};

// helper: shift YYYY-MM-DD safely
function shiftDate(dateStr, offset) {
    const d = new Date(dateStr);
    d.setDate(d.getDate() + offset);
    return d.toISOString().slice(0, 10);
}