import { EmbedBuilder } from 'discord.js';
import {
  embedHasContent,
  mapEmbedTextFields,
  type EmbedTextField,
  type WelcomeEmbed
} from '@nexumi/shared';

function isHttpUrl(value: string | undefined): value is string {
  if (!value) {
    return false;
  }
  try {
    const url = new URL(value);
    return url.protocol === 'http:' || url.protocol === 'https:';
  } catch {
    return false;
  }
}

export interface ApplyEmbedOptions {
  /**
   * Called for every text/URL field before applying to the builder.
   * `field` lets callers render `{user}` as a mention in the description
   * but as a plain display name in title/author/footer.
   */
  renderText: (value: string, field: EmbedTextField) => string;
  /**
   * Used when `thumbnailUrl` is unset (Welcome default: member avatar).
   * Pass `null` to force no thumbnail.
   */
  defaultThumbnailUrl?: string | null;
}

/**
 * Builds a discord.js EmbedBuilder from our shared WelcomeEmbed payload.
 * Invalid/non-http URLs are skipped so bad dashboard input never crashes send.
 */
export function buildEmbedFromPayload(
  raw: WelcomeEmbed | null | undefined,
  options: ApplyEmbedOptions
): EmbedBuilder | null {
  if (!raw || (!embedHasContent(raw) && raw.color === undefined)) {
    return null;
  }

  const data = mapEmbedTextFields(raw, options.renderText);
  const embed = new EmbedBuilder();

  if (data.color !== undefined) {
    embed.setColor(data.color);
  }
  if (data.title) {
    embed.setTitle(data.title);
  }
  if (data.description) {
    embed.setDescription(data.description);
  }
  if (isHttpUrl(data.url)) {
    embed.setURL(data.url);
  }
  if (data.authorName) {
    embed.setAuthor({
      name: data.authorName,
      iconURL: isHttpUrl(data.authorIconUrl) ? data.authorIconUrl : undefined,
      url: isHttpUrl(data.authorUrl) ? data.authorUrl : undefined
    });
  }

  const thumbnail =
    isHttpUrl(data.thumbnailUrl)
      ? data.thumbnailUrl
      : options.defaultThumbnailUrl === null
        ? undefined
        : options.defaultThumbnailUrl;
  if (isHttpUrl(thumbnail)) {
    embed.setThumbnail(thumbnail);
  }

  if (isHttpUrl(data.imageUrl)) {
    embed.setImage(data.imageUrl);
  }
  if (data.footerText) {
    embed.setFooter({
      text: data.footerText,
      iconURL: isHttpUrl(data.footerIconUrl) ? data.footerIconUrl : undefined
    });
  }
  if (data.timestamp) {
    embed.setTimestamp(new Date());
  }

  return embed;
}
