"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.browseTags = browseTags;
const types_1 = require("@playdrop/types");
const commandContext_1 = require("../commandContext");
const messages_1 = require("../messages");
function normalizeGroupSlug(value) {
    const normalized = typeof value === 'string' ? value.trim().toLowerCase() : '';
    return normalized.length > 0 ? normalized : null;
}
function normalizeTargetKind(value) {
    const normalized = typeof value === 'string' ? value.trim().toUpperCase() : '';
    if (!normalized) {
        return null;
    }
    return types_1.SAVED_ITEM_KIND_VALUES.includes(normalized)
        ? normalized
        : null;
}
function formatAllowedTargetKinds(kinds) {
    if (!Array.isArray(kinds) || kinds.length === 0) {
        return 'all';
    }
    return kinds.join(', ');
}
async function browseTags(options) {
    const groupSlug = normalizeGroupSlug(options.group);
    const targetKind = normalizeTargetKind(options.kind);
    if (options.group && (!groupSlug || !(0, types_1.isValidTagSlug)(groupSlug))) {
        (0, messages_1.printErrorWithHelp)(`Invalid group slug "${options.group}".`, ['Use lowercase letters, numbers, and hyphens only.'], { command: 'tags browse' });
        process.exitCode = 1;
        return;
    }
    if (options.kind && !targetKind) {
        (0, messages_1.printErrorWithHelp)(`Unsupported target kind "${options.kind}".`, [`Use one of: ${types_1.SAVED_ITEM_KIND_VALUES.join(', ')}.`], { command: 'tags browse' });
        process.exitCode = 1;
        return;
    }
    await (0, commandContext_1.withPublicEnvironment)('tags browse', async ({ client }) => {
        const response = await client.fetchTags({
            ...(groupSlug ? { groupSlug } : {}),
            ...(targetKind ? { targetKind } : {}),
        });
        if (options.json) {
            console.log(JSON.stringify(response, null, 2));
            return;
        }
        if (response.groups.length === 0) {
            console.log('No tags found.');
            return;
        }
        for (const [groupIndex, group] of response.groups.entries()) {
            if (groupIndex > 0) {
                console.log('');
            }
            console.log(`${group.displayName} (${group.slug})`);
            console.log(`Allowed targets: ${formatAllowedTargetKinds(group.allowedTargetKinds)}`);
            for (const tag of group.tags) {
                console.log(`${tag.ref}  ${tag.displayName}`);
            }
        }
    });
}
