import {
  SlashCommandSubcommandBuilder,
  type ChatInputCommandInteraction,
} from 'discord.js';
import { api } from '../api-client.js';
import { buildDeployEmbed } from '../embeds/deploy-notification.js';
import { logger } from '../logger.js';

export const data = new SlashCommandSubcommandBuilder()
  .setName('deploy')
  .setDescription('Deploy a pipeline to staging or production')
  .addStringOption((opt) =>
    opt
      .setName('pipeline_id')
      .setDescription('The pipeline to deploy')
      .setRequired(true),
  )
  .addStringOption((opt) =>
    opt
      .setName('target')
      .setDescription('Deploy target')
      .setRequired(true)
      .addChoices(
        { name: 'Staging', value: 'staging' },
        { name: 'Production', value: 'production' },
      ),
  )
  .addBooleanOption((opt) =>
    opt
      .setName('dry_run')
      .setDescription('Preview without actually deploying')
      .setRequired(false),
  );

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

  const pipelineId = interaction.options.getString('pipeline_id', true);
  const target = interaction.options.getString('target', true) as 'staging' | 'production';
  const dryRun = interaction.options.getBoolean('dry_run') ?? false;

  try {
    // Get pipeline info for display
    const pipeline = await api.getPipeline(pipelineId);

    if (dryRun) {
      await interaction.editReply({
        content: `🔍 **Dry Run** — Would deploy **${pipeline.name}** to ${target === 'production' ? '🚀 Production' : '🎭 Staging'}\n` +
          `Pipeline: \`${pipelineId}\`\nCurrent Stage: ${pipeline.currentStage}\n\n` +
          `_No changes were made. Remove \`dry_run\` to actually deploy._`,
      });
      return;
    }

    // Initiate deploy
    const result = await api.deploy(pipelineId, target);

    const embed = buildDeployEmbed({
      pipelineId: pipeline.id,
      pipelineName: pipeline.name,
      target,
      version: result.deployId, // Use deploy ID as version fallback
      status: result.status,
      url: result.url,
      error: result.error,
      triggeredBy: interaction.user.tag,
    });

    await interaction.editReply(embed);

    logger.info(`Deploy initiated for ${pipeline.name} → ${target} by ${interaction.user.tag}`);
  } catch (error) {
    logger.error(`Failed to deploy pipeline ${pipelineId}:`, error);
    await interaction.editReply({
      content: `❌ Deploy failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
    });
  }
}
