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

export const data = new SlashCommandSubcommandBuilder()
  .setName('reject')
  .setDescription('Reject a pending task with a reason')
  .addStringOption((opt) =>
    opt
      .setName('task_id')
      .setDescription('The task ID to reject')
      .setRequired(true),
  )
  .addStringOption((opt) =>
    opt
      .setName('reason')
      .setDescription('Why this is being rejected')
      .setRequired(true),
  )
  .addStringOption((opt) =>
    opt
      .setName('changes')
      .setDescription('Requested changes (comma-separated)')
      .setRequired(false),
  );

export async function execute(interaction: ChatInputCommandInteraction): Promise<void> {
  await interaction.deferReply();

  const taskId = interaction.options.getString('task_id', true);
  const reason = interaction.options.getString('reason', true);
  const changesRaw = interaction.options.getString('changes');
  const requestedChanges = changesRaw
    ? changesRaw.split(',').map((s) => s.trim()).filter(Boolean)
    : undefined;

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

    if (task.status === 'completed') {
      await interaction.editReply({
        content: `⚠️ Task \`${taskId}\` has already been completed (decision: ${task.decision}).`,
      });
      return;
    }

    // Find associated approval
    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 /factory reject by ${interaction.user.tag}`,
        requestedChanges,
      });
    }

    const updatedTask = await api.getTask(taskId);
    const embed = buildRejectedEmbed(updatedTask, interaction.user.id, reason);
    await interaction.editReply(embed);

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