import chalk from 'chalk'
import { formatReceiptLine, listReceipts } from '../../services/receipts/receipts.js'
import type { LocalCommandCall } from '../../types/command.js'

const DEFAULT_LIMIT = 20
const MAX_LIMIT = 200

function parseLimit(args: string): number {
  const trimmed = args.trim()
  if (!trimmed) return DEFAULT_LIMIT
  const n = parseInt(trimmed, 10)
  if (!Number.isFinite(n) || n <= 0) return DEFAULT_LIMIT
  return Math.min(n, MAX_LIMIT)
}

export const call: LocalCommandCall = async (args: string) => {
  const limit = parseLimit(args)
  const receipts = await listReceipts(limit)

  if (receipts.length === 0) {
    return {
      type: 'text',
      value: 'No receipts yet. A receipt is emitted on each successful file edit or write.',
    }
  }

  const header = `Showing ${receipts.length} most recent receipt${receipts.length === 1 ? '' : 's'}:`
  const body = receipts.map((r) => '  ' + formatReceiptLine(r)).join('\n')
  return { type: 'text', value: chalk.dim(`${header}\n${body}`) }
}
