import { SlashCommandBuilder } from "discord.js";
import type { CommandModule } from "../../discord/types.js";
import { newsService } from "../../services/news/news-service.js";

export const newsCommand: CommandModule = {
  data: new SlashCommandBuilder()
    .setName("news")
    .setDescription("구글 뉴스 최신 10개를 보여줍니다")
    .addStringOption((opt) =>
      opt
        .setName("query")
        .setDescription("검색 키워드 (생략 시 전체 뉴스)")
        .setRequired(false),
    ),
  async execute(interaction) {
    const query = interaction.options.getString("query") || "";
    await interaction.deferReply();

    try {
      const items = await newsService.fetchGoogleNews(query, 10);
      const title = query ? `구글 뉴스: ${query}` : "구글 뉴스: 최신";
      const chunks = newsService.toDiscordMessageChunks(title, items, 1900);
      await interaction.editReply({ content: chunks[0], allowedMentions: { parse: [] } });
      for (let i = 1; i < chunks.length; i += 1) {
        await interaction.followUp({ content: chunks[i], allowedMentions: { parse: [] } });
      }
    } catch (error) {
      await interaction.editReply(
        `뉴스 조회 실패: ${error instanceof Error ? error.message : "알 수 없는 오류"}`,
      );
    }
  },
};
