import type { Context } from 'telegraf';
import type { TrelloClient } from '../trello/client.js';
import { escapeMarkdown, link } from '../utils/format.js';

export function makeBtwHandler(trello: TrelloClient, btwListId?: string) {
  return async function btwHandler(ctx: Context): Promise<void> {
    const text = ctx.message && 'text' in ctx.message ? ctx.message.text : '';
    const task = text.replace(/^\/btw\s*/i, '').trim();

    if (!task) {
      await ctx.reply('Usage: /btw <card title>\nExample: /btw Fix login bug on mobile');
      return;
    }

    const listId = await trello.resolveBtwListId(btwListId);
    const card = await trello.createCard(task, listId);
    await ctx.replyWithMarkdownV2(
      `✅ Card added: ${link(escapeMarkdown(card.name), card.shortUrl)}`,
    );
  };
}
