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

export const data = new SlashCommandSubcommandBuilder()
  .setName('approve')
  .setDescription('Approve a pending task')
  .addStringOption((opt) =>
    opt
      .setName('task_id')
      .setDescription('The task ID to approve')
      .setRequired(true),
  )
  .addStringOption((opt) =>
    opt
      .setName('notes')
      .setDescription('Optional approval notes')
      .setRequired(false),
  );

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

  const taskId = interaction.options.getString('task_id', true);
  const notes = interaction.options.getString('notes') ?? undefined;

  try {
    // Get the task
    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.approveApproval(approval.id, {
        notes: notes
          ? `${notes}\n\n— Approved via /factory approve by ${interaction.user.tag}`
          : `Approved via /factory approve by ${interaction.user.tag}`,
      });
    }

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

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