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

/**
 * Handle Discord modal submissions — primarily rejection reason modals.
 */
export async function handleModal(interaction: ModalSubmitInteraction): Promise<void> {
  const [action, ...args] = interaction.customId.split(':');

  switch (action) {
    case 'reject-modal':
      await handleRejectSubmission(interaction, args[0]);
      break;
    default:
      await interaction.reply({
        content: `Unknown modal: ${action}`,
        ephemeral: true,
      });
  }
}

async function handleRejectSubmission(
  interaction: ModalSubmitInteraction,
  taskId: string,
): Promise<void> {
  await interaction.deferUpdate();

  try {
    const reason = interaction.fields.getTextInputValue('reason');
    const changesRaw = interaction.fields.getTextInputValue('requested_changes');
    const requestedChanges = changesRaw
      ? changesRaw.split('\n').map((s) => s.trim()).filter(Boolean)
      : undefined;

    // Find and reject the approval
    const task = await api.getTask(taskId);
    const approvals = await api.listApprovals({
      pipelineId: task.pipelineId ?? undefined,
      status: 'pending',
    });
    const approval = approvals.find((a) => a.taskId === taskId);

    if (approval) {
      await api.rejectApproval(approval.id, {
        reason: `${reason}\n\n— Rejected via Discord by ${interaction.user.tag}`,
        requestedChanges,
      });
    }

    // Update the message embed
    const updatedTask = await api.getTask(taskId);
    const newEmbed = buildRejectedEmbed(updatedTask, interaction.user.id, reason);
    await interaction.editReply(newEmbed);

    logger.info(
      `Task ${taskId} rejected by ${interaction.user.tag}: ${reason}`,
    );
  } catch (error) {
    logger.error(`Failed to reject task ${taskId}:`, error);
    await interaction.followUp({
      content: `❌ Failed to reject task: ${error instanceof Error ? error.message : 'Unknown error'}`,
      ephemeral: true,
    });
  }
}
