const { mClient } = require("..");

async function getMember(client, userId) {
	const guild = client.guilds.cache.get(process.env.D_GuildID);
	if (!guild) return null;

	// cache first (fast path)
	let member = guild.members.cache.get(userId);

	// fallback (safe path)
	if (!member) {
		member = await guild.members.fetch(userId).catch(() => null);
	}

	return member;
}

module.exports = {
	name: 'timerComplete',

	async execute(timer, client) {
		const member = await getMember(client, timer.assignedUser);
		if (!member) return;

		await member.send(
			`❌ Timer ran out: **${timer.topic}** ...Re-assigning randomly...`
		).catch(() => { });

		// Reset Timer, Reassign Randomly
		const db = mClient.db('neo-db')
		const wgeColl = db.collection('timer_wge')

		// Randomizer Function
		const participateColl = db.collection('items_wge')
		const randomParticipant = await participateColl.aggregate([
			{ $match: { status: true } },
			{ $sample: { size: 1 } }
		]).toArray()

		if (!randomParticipant.length) { return interaction.reply({ content: 'No one else is participating!' }) }

		const wge = await wgeColl.findOne({
			$and: [
				{ debug: false },
				{ state: 'running' }
			]
		})

		const channelColl = db.collection('config_channels')
		const guild = await client.guilds.cache.get(process.env.D_GuildID);
		const wgeChannel = await channelColl.findOne({
			$and: [
				{ purpose: 'wge' },
				{ guildID: process.env.D_GuildID }
			]
		})
		
		const channel = await client.channels.cache.get(wgeChannel.channelID)

		random = await guild.members.fetch(randomParticipant[0].userID)
		wgeAssignedUser = random.user

		await wgeColl.deleteOne({
			_id: wge._id
		})

		const wgeDefaultAssignedTime = 7 * 24 * 60 * 60 * 1000; // 7 days in ms

		channel.send({
			content: `The Timer for <@${wge.assignedUser}> has run out! Assigning randomly... \r\n<@${wgeAssignedUser.id}> is the next expert! Their topic still is **${wge.topic}**`
		})

		await wgeColl.insertOne({
			assignedUser: wgeAssignedUser.id,
			assigningUser: wge.assigningUser,

			startedAt: Date.now(),
			timeRemaining: wgeDefaultAssignedTime,

			state: 'running',

			notifications: {
				half: false,
				day24: false,
				complete: false
			},

			topic: wge.topic,
			debug: false,

			createdAt: new Date()
		});

	}
};