import type { StringSelectMenuInteraction } from 'discord.js';
import { api } from '../api-client.js';
import { buildApprovalRequestEmbed } from '../embeds/approval-request.js';
import { logger } from '../logger.js';

/**
 * Handle Discord select menu interactions.
 */
export async function handleSelectMenu(
  interaction: StringSelectMenuInteraction,
): Promise<void> {
  const [action] = interaction.customId.split(':');

  switch (action) {
    case 'batch-select-review':
      await handleBatchSelectReview(interaction);
      break;
    default:
      await interaction.reply({
        content: `Unknown select menu: ${action}`,
        ephemeral: true,
      });
  }
}

async function handleBatchSelectReview(
  interaction: StringSelectMenuInteraction,
): Promise<void> {
  const taskId = interaction.values[0];
  if (!taskId) {
    await interaction.reply({
      content: 'No task selected.',
      ephemeral: true,
    });
    return;
  }

  await interaction.deferReply({ ephemeral: true });

  try {
    const task = await api.getTask(taskId);
    const embed = buildApprovalRequestEmbed(task);

    await interaction.editReply({
      content: `📋 Review task: **${task.title}**`,
      ...embed,
    });
  } catch (error) {
    logger.error(`Failed to load task ${taskId} for review:`, error);
    await interaction.editReply({
      content: `❌ Failed to load task: ${error instanceof Error ? error.message : 'Unknown error'}`,
    });
  }
}
