"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const BaseCommand_1 = require("../../BaseCommand");
const core_1 = require("@oclif/core");
class CardCheckItem extends BaseCommand_1.BaseCommand {
    async run() {
        const resolved = await this.resolveCheckItem(this.lookups.card, this.flags.item, this.flags.checklist);
        const result = await this.client.cards.updateCardCheckItem({
            id: this.lookups.card,
            idCheckItem: resolved.itemId,
            ...(resolved.checklistId && { idChecklist: resolved.checklistId }),
            state: this.flags.state,
        });
        this.output(result);
    }
    async resolveCheckItem(cardId, item, checklist) {
        // If the item looks like a Trello ID already, use it directly
        if (/^[a-f0-9]{24}$/.test(item)) {
            const checklistId = checklist && /^[a-f0-9]{24}$/.test(checklist) ? checklist : undefined;
            return { itemId: item, checklistId };
        }
        const checklists = (await this.client.cards.getCardChecklists({
            id: cardId,
        }));
        // Optionally filter to a specific checklist
        const scope = checklist
            ? checklists.filter((cl) => cl.name === checklist || cl.id === checklist)
            : checklists;
        if (checklist && scope.length === 0) {
            this.error(`No checklist found matching "${checklist}"`);
        }
        const matches = scope.flatMap((cl) => {
            var _a;
            return ((_a = cl.checkItems) !== null && _a !== void 0 ? _a : [])
                .filter((ci) => ci.name === item)
                .map((ci) => ({ itemId: ci.id, checklistId: cl.id }));
        });
        if (matches.length === 0) {
            this.error(`No check item found with name "${item}"`);
        }
        if (matches.length > 1) {
            this.error(`Multiple check items found with name "${item}". Use --checklist to disambiguate.`);
        }
        return matches[0];
    }
    toData(data) {
        return {
            id: data.id,
            name: data.name,
            state: data.state,
        };
    }
}
CardCheckItem.description = "Update a checklist item on a card";
CardCheckItem.flags = {
    board: core_1.Flags.string({ required: true }),
    list: core_1.Flags.string({ required: true }),
    card: core_1.Flags.string({ required: true }),
    checklist: core_1.Flags.string({
        description: "Checklist name or ID to narrow item lookup when multiple checklists share the same item name",
    }),
    item: core_1.Flags.string({ required: true }),
    state: core_1.Flags.option({
        required: true,
        options: ["complete", "incomplete"],
    })(),
};
exports.default = CardCheckItem;
