import {
  EmbedBuilder,
  ActionRowBuilder,
  ButtonBuilder,
  ButtonStyle,
  type MessageCreateOptions,
} from 'discord.js';
import { COLORS } from '../config.js';

interface DeployData {
  pipelineId: string;
  pipelineName: string;
  target: 'staging' | 'production';
  version: string;
  status: 'started' | 'succeeded' | 'failed';
  url?: string;
  error?: string;
  triggeredBy?: string;
}

/**
 * Build a deploy notification embed for #factory-deploys.
 */
export function buildDeployEmbed(data: DeployData): MessageCreateOptions {
  const isProduction = data.target === 'production';
  const targetEmoji = isProduction ? '🚀' : '🎭';
  const targetLabel = isProduction ? 'Production' : 'Staging';

  let title: string;
  let color: number;
  let statusDescription: string;

  switch (data.status) {
    case 'started':
      title = `${targetEmoji} Deploy Started`;
      color = COLORS.info;
      statusDescription = `Deploying **${data.pipelineName}** v${data.version} to ${targetLabel}...`;
      break;
    case 'succeeded':
      title = `✅ Deploy Succeeded`;
      color = COLORS.success;
      statusDescription = `**${data.pipelineName}** v${data.version} is live on ${targetLabel}!`;
      break;
    case 'failed':
      title = `❌ Deploy Failed`;
      color = COLORS.danger;
      statusDescription = `Failed to deploy **${data.pipelineName}** v${data.version} to ${targetLabel}.`;
      break;
  }

  const embed = new EmbedBuilder()
    .setTitle(title!)
    .setDescription(statusDescription!)
    .addFields(
      { name: 'Pipeline', value: data.pipelineName, inline: true },
      { name: 'Target', value: `${targetEmoji} ${targetLabel}`, inline: true },
      { name: 'Version', value: `v${data.version}`, inline: true },
    )
    .setColor(color!)
    .setFooter({ text: `Pipeline ID: ${data.pipelineId}` })
    .setTimestamp();

  // Add URL if deploy succeeded
  if (data.status === 'succeeded' && data.url) {
    embed.addFields({ name: 'URL', value: `[Open →](${data.url})`, inline: true });
  }

  // Add error if deploy failed
  if (data.status === 'failed' && data.error) {
    embed.addFields({
      name: 'Error',
      value: `\`\`\`\n${data.error.slice(0, 1000)}\n\`\`\``,
    });
  }

  // Add triggered by
  if (data.triggeredBy) {
    embed.addFields({ name: 'Triggered By', value: data.triggeredBy, inline: true });
  }

  // Buttons for failed deploys
  const components: ActionRowBuilder<ButtonBuilder>[] = [];
  if (data.status === 'failed') {
    const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
      new ButtonBuilder()
        .setCustomId(`deploy-retry:${data.pipelineId}:${data.target}`)
        .setLabel('🔄 Retry Deploy')
        .setStyle(ButtonStyle.Primary),
      new ButtonBuilder()
        .setCustomId(`details:${data.pipelineId}`)
        .setLabel('📋 View Logs')
        .setStyle(ButtonStyle.Secondary),
    );
    components.push(buttons);
  }

  // Content for production deploys
  const content = data.status === 'succeeded' && isProduction
    ? `🎉 **${data.pipelineName}** is now live in production!`
    : data.status === 'failed' && isProduction
      ? `⚠️ Production deploy failed for **${data.pipelineName}** — needs attention`
      : undefined;

  return { content, embeds: [embed], components };
}
