import {
  SlashCommandSubcommandBuilder,
  type ChatInputCommandInteraction,
} from 'discord.js';
import { api } from '../api-client.js';
import { buildPipelineListEmbed, buildPipelineStatusEmbed } from '../embeds/pipeline-status.js';
import { logger } from '../logger.js';

export const data = new SlashCommandSubcommandBuilder()
  .setName('pipelines')
  .setDescription('List active pipelines')
  .addStringOption((opt) =>
    opt
      .setName('status')
      .setDescription('Filter by status')
      .setRequired(false)
      .addChoices(
        { name: 'Active', value: 'active' },
        { name: 'Paused', value: 'paused' },
        { name: 'Completed', value: 'completed' },
        { name: 'Failed', value: 'failed' },
      ),
  )
  .addStringOption((opt) =>
    opt
      .setName('pipeline_id')
      .setDescription('Get details for a specific pipeline')
      .setRequired(false),
  );

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

  const status = interaction.options.getString('status') ?? 'active';
  const pipelineId = interaction.options.getString('pipeline_id');

  try {
    // If specific pipeline requested
    if (pipelineId) {
      const pipeline = await api.getPipeline(pipelineId);
      const stages = await api.getPipelineStages(pipelineId);
      const embed = buildPipelineStatusEmbed(pipeline, stages);
      await interaction.editReply(embed);
      return;
    }

    // List all matching pipelines
    const pipelines = await api.listPipelines({ status, limit: 25 });
    const embed = buildPipelineListEmbed(pipelines);
    await interaction.editReply(embed);
  } catch (error) {
    logger.error('Failed to fetch pipelines:', error);
    await interaction.editReply({
      content: `❌ Failed to fetch pipelines: ${error instanceof Error ? error.message : 'Unknown error'}`,
    });
  }
}
