const { PermissionFlagsBits, ApplicationCommandOptionType } = require('discord.js')

const siteApiClient = require('../../site/siteApiClient')
const newsAnnounce = require('../newsAnnounce')

function siteOrigin() {
  const base = process.env.SITE_PUBLIC_URL || 'http://localhost:3000/api/v1/public'
  return new URL(base).origin
}

module.exports = {
  data: {
    name: 'announce',
    description: 'Re-post or boost an existing news item.',
    default_member_permissions: PermissionFlagsBits.ManageGuild.toString(),
    options: [
      { name: 'post', description: 'News post id or slug', type: ApplicationCommandOptionType.String, required: true },
    ],
  },
  async execute(interaction) {
    const idOrSlug = interaction.options.getString('post', true)
    await interaction.deferReply({ ephemeral: true })

    const result = await siteApiClient.getNewsPost(idOrSlug)
    if (result.maintenance) {
      await interaction.editReply({ content: `Can't reach the site right now: ${result.message || 'maintenance mode'}` })
      return
    }
    if (!result.ok) {
      await interaction.editReply({ content: `Couldn't find that news post ("${idOrSlug}").` })
      return
    }

    const post = result.data
    const origin = siteOrigin()
    try {
      await newsAnnounce.postAnnounce(interaction.client, interaction.guildId, {
        title: post.title,
        excerpt: post.excerpt,
        url: `${origin}/site/news`,
        // image_url is stored relative — Discord embeds require an absolute URL.
        imageUrl: post.image_url ? new URL(post.image_url, origin).toString() : null,
      })
      await interaction.editReply({ content: `Posted "${post.title}" to the news channel.` })
    } catch (err) {
      await interaction.editReply({ content: `Couldn't post: ${err.message}` })
    }
  },
}
