import type { Context } from 'telegraf';
import type { TrelloClient } from '../trello/client.js';
import type { TrelloCard } from '../trello/types.js';
import { bold, cardLine, escapeMarkdown } from '../utils/format.js';
import { sendChunked } from '../agent/chunker.js';

export function makeListHandler(trello: TrelloClient) {
  return async function listHandler(ctx: Context): Promise<void> {
    const [lists, cards] = await Promise.all([trello.getLists(), trello.getCards()]);

    if (lists.length === 0) {
      await ctx.reply('No open lists found on the board.');
      return;
    }

    const sections: string[] = [`*📋 Board Overview*\n`];

    for (const list of lists) {
      const listCards: TrelloCard[] = cards.filter((c) => c.idList === list.id);
      const header = bold(`${escapeMarkdown(list.name)} \\(${listCards.length}\\)`);
      if (listCards.length === 0) {
        sections.push(`${header}\n_empty_`);
      } else {
        const rows = listCards
          .slice(0, 15)
          .map((c) => cardLine(c.name, c.shortUrl))
          .join('\n');
        sections.push(`${header}\n${rows}`);
      }
    }

    await sendChunked(ctx, sections.join('\n\n'));
  };
}
