import {
  ABOUT_REDIS_KEY,
  BotAboutConfigSchema,
  expandBracketChannelMentions,
  parseMessageComponentsV2,
  t,
  type BotAboutConfig,
  type Locale,
  type WelcomeEmbed
} from '@nexumi/shared';
import type { InteractionReplyOptions, MessageCreateOptions } from 'discord.js';
import { EmbedBuilder } from 'discord.js';
import { buildComponentsV2Payload } from '../../lib/components-v2-payload.js';
import { buildEmbedFromPayload } from '../../lib/embed-payload.js';
import { redis } from '../../redis.js';
import type { BotContext } from '../../types.js';

const NEXUMI_COLOR = 0x6366f1;

function parseEmbed(raw: unknown): WelcomeEmbed | null {
  if (!raw || typeof raw !== 'object') {
    return null;
  }
  return raw as WelcomeEmbed;
}

export async function readAboutConfig(context: BotContext): Promise<BotAboutConfig> {
  const cached = await redis.get(ABOUT_REDIS_KEY);
  if (cached) {
    const parsed = BotAboutConfigSchema.safeParse(JSON.parse(cached));
    if (parsed.success) {
      return parsed.data;
    }
  }

  const row = await context.prisma.botAboutConfig.upsert({
    where: { id: 'singleton' },
    create: { id: 'singleton' },
    update: {}
  });
  const config = BotAboutConfigSchema.parse({
    enabled: row.enabled,
    messageType: row.messageType,
    content: row.content,
    embed: parseEmbed(row.embed),
    components: parseMessageComponentsV2(row.components)
  });
  await redis.set(ABOUT_REDIS_KEY, JSON.stringify(config));
  return config;
}

function defaultAboutReply(locale: Locale): InteractionReplyOptions {
  return {
    embeds: [
      new EmbedBuilder()
        .setTitle(t(locale, 'core.about.defaultTitle'))
        .setDescription(t(locale, 'core.about.defaultBody'))
        .setColor(NEXUMI_COLOR)
        .setFooter({ text: 'Nexumi' })
    ]
  };
}

export async function buildAboutReply(
  context: BotContext,
  locale: Locale
): Promise<InteractionReplyOptions | MessageCreateOptions> {
  const config = await readAboutConfig(context);
  if (!config.enabled) {
    return { content: t(locale, 'core.about.disabled'), ephemeral: true };
  }

  const renderText = (value: string) => expandBracketChannelMentions(value);

  if (config.messageType === 'COMPONENTS_V2') {
    const payload = buildComponentsV2Payload(config.components, {
      source: 'a',
      ref: 'singleton',
      renderText
    });
    if (payload) {
      return payload;
    }
  }

  if (config.messageType === 'EMBED') {
    const embed = buildEmbedFromPayload(config.embed, { renderText });
    if (embed) {
      return { embeds: [embed] };
    }
  }

  if (config.messageType === 'TEXT' && config.content?.trim()) {
    return { content: renderText(config.content) };
  }

  return defaultAboutReply(locale);
}
