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

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

// Public command — no default_member_permissions restriction. Read-only:
// searches wiki titles/content and links to the best match. Never posts to or
// edits the wiki. Category-scoped search (spec's optional "/wiki spells
// fireball") is deferred — the site's public search endpoint currently
// ignores category filters whenever a text query is given.
function siteOrigin() {
  const base = process.env.SITE_PUBLIC_URL || 'http://localhost:3000/api/v1/public'
  return new URL(base).origin
}

module.exports = {
  data: {
    name: 'wiki',
    description: 'Search the wiki.',
    options: [{ name: 'query', description: 'What to search for', type: ApplicationCommandOptionType.String, required: true }],
  },
  async execute(interaction) {
    const query = interaction.options.getString('query', true)
    await interaction.deferReply()

    const result = await siteApiClient.searchWiki(query)
    if (result.maintenance) {
      await interaction.editReply({ content: `The wiki is unavailable right now: ${result.message || 'maintenance mode'}` })
      return
    }
    if (!result.ok || !result.data || result.data.length === 0) {
      await interaction.editReply({ content: `No wiki results for "${query}".` })
      return
    }

    const best = result.data[0]
    const url = `${siteOrigin()}/wiki/${best.slug}`
    const content = best.excerpt ? `**${best.title}**\n${best.excerpt}\n${url}` : `**${best.title}**\n${url}`
    await interaction.editReply({ content })
  },
}
