"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.browseCreations = browseCreations;
exports.updateCreationApp = updateCreationApp;
exports.deleteCreationApp = deleteCreationApp;
exports.setCurrentCreationAppVersion = setCurrentCreationAppVersion;
exports.publishCreationAppVersion = publishCreationAppVersion;
exports.unpublishCreationAppVersion = unpublishCreationAppVersion;
exports.deleteCreationAppVersion = deleteCreationAppVersion;
exports.updateCreationAsset = updateCreationAsset;
exports.deleteCreationAsset = deleteCreationAsset;
exports.setCurrentCreationAssetVersion = setCurrentCreationAssetVersion;
exports.publishCreationAssetVersion = publishCreationAssetVersion;
exports.unpublishCreationAssetVersion = unpublishCreationAssetVersion;
exports.deleteCreationAssetVersion = deleteCreationAssetVersion;
exports.updateCreationAssetPack = updateCreationAssetPack;
exports.deleteCreationAssetPack = deleteCreationAssetPack;
exports.setCurrentCreationAssetPackVersion = setCurrentCreationAssetPackVersion;
exports.publishCreationAssetPackVersion = publishCreationAssetPackVersion;
exports.unpublishCreationAssetPackVersion = unpublishCreationAssetPackVersion;
exports.deleteCreationAssetPackVersion = deleteCreationAssetPackVersion;
const types_1 = require("@playdrop/types");
const commandContext_1 = require("../commandContext");
const errors_1 = require("../errors");
const messages_1 = require("../messages");
const output_1 = require("../output");
const refs_1 = require("../refs");
const MERGED_PAGE_SIZE = 100;
function parseBrowseKind(raw) {
    if (!raw || raw.trim().length === 0) {
        return 'all';
    }
    const normalized = raw.trim().toLowerCase();
    if (normalized === 'app' || normalized === 'asset' || normalized === 'asset-pack' || normalized === 'all') {
        return normalized;
    }
    return null;
}
function parsePositiveInteger(raw, label, fallback) {
    if (raw === undefined) {
        return fallback;
    }
    const parsed = typeof raw === 'number' ? raw : Number.parseInt(String(raw), 10);
    if (!Number.isInteger(parsed) || parsed < 0) {
        return null;
    }
    if (label === 'limit' && parsed <= 0) {
        return null;
    }
    return parsed;
}
async function resolveCreator(client, rawCreator, command) {
    let creator;
    try {
        creator = (0, refs_1.parseCreatorOption)(rawCreator);
    }
    catch {
        (0, messages_1.printErrorWithHelp)('The --creator value is invalid.', ['Use me or a creator slug without path separators.'], { command });
        process.exitCode = 1;
        return null;
    }
    if (creator !== 'me') {
        return creator;
    }
    const response = await client.me();
    const username = response.user?.username?.trim();
    if (!username) {
        (0, messages_1.printErrorWithHelp)('Could not resolve your current creator account.', ['Run "playdrop auth whoami" to confirm your session, then retry.'], { command });
        process.exitCode = 1;
        return null;
    }
    return username;
}
function parseRevision(raw, command) {
    const normalized = raw.trim().toLowerCase();
    const numeric = normalized.startsWith('r') ? normalized.slice(1) : normalized;
    const parsed = Number.parseInt(numeric, 10);
    if (!Number.isInteger(parsed) || parsed <= 0) {
        (0, messages_1.printErrorWithHelp)('Revision must be a positive integer or r-prefixed revision label.', ['Example: r2'], { command });
        process.exitCode = 1;
        return null;
    }
    return parsed;
}
function parseVersion(raw, command) {
    const normalized = raw.trim();
    if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(normalized)) {
        (0, messages_1.printErrorWithHelp)('Version must use semantic version format x.y.z.', ['Example: 1.2.0'], { command });
        process.exitCode = 1;
        return null;
    }
    return normalized;
}
function kindLabel(kind) {
    return kind === 'all' ? 'content' : kind === 'asset-pack' ? 'asset packs' : `${kind}s`;
}
function formatCountValue(value) {
    return value.toLocaleString('en-US');
}
function buildCountsSuffix(item) {
    const parts = [];
    if (item.kind === 'app' && 'playCount' in item.item && typeof item.item.playCount === 'number') {
        if (typeof item.item.viewCount === 'number') {
            parts.push(`view ${formatCountValue(item.item.viewCount)}`);
        }
        parts.push(`launch ${formatCountValue(item.item.playCount)}`);
    }
    if (item.kind === 'asset') {
        if ('viewCount' in item.item && typeof item.item.viewCount === 'number') {
            parts.push(`view ${formatCountValue(item.item.viewCount)}`);
        }
    }
    if (item.kind === 'asset-pack' && 'downloadCount' in item.item && typeof item.item.downloadCount === 'number') {
        parts.push(`download ${formatCountValue(item.item.downloadCount)}`);
    }
    if (typeof item.item.likeCount === 'number') {
        parts.push(`like ${formatCountValue(item.item.likeCount)}`);
    }
    if (typeof item.item.remixCount === 'number') {
        parts.push(`remix ${formatCountValue(item.item.remixCount)}`);
    }
    if (typeof item.item.commentCount === 'number') {
        parts.push(`comment ${formatCountValue(item.item.commentCount)}`);
    }
    return parts.length > 0 ? ` | ${parts.join(' | ')}` : '';
}
async function collectPaginatedItems(fetchPage) {
    const items = [];
    let offset = 0;
    let lastPagination = null;
    while (true) {
        const page = await fetchPage(MERGED_PAGE_SIZE, offset);
        items.push(...page.items);
        lastPagination = page.pagination;
        if (!page.pagination.hasMore) {
            break;
        }
        if (page.pagination.limit <= 0) {
            throw new Error('invalid_pagination_limit');
        }
        offset += page.pagination.limit;
    }
    return {
        items,
        pagination: lastPagination ?? { limit: MERGED_PAGE_SIZE, offset: 0, count: 0, hasMore: false },
    };
}
function sliceMergedItems(items, limit, offset) {
    const count = items.length;
    return {
        items: items.slice(offset, offset + limit),
        pagination: {
            limit,
            offset,
            count,
            hasMore: offset + limit < count,
        },
    };
}
function requirePagination(pagination, context) {
    if (!pagination) {
        throw new Error(`missing_pagination:${context}`);
    }
    return pagination;
}
function parseManagedName(raw, command) {
    try {
        return (0, refs_1.parseScopedName)(raw ?? '', 'name');
    }
    catch {
        (0, messages_1.printErrorWithHelp)('A valid name is required.', ['Names cannot be empty and cannot contain path separators.'], { command });
        process.exitCode = 1;
        return null;
    }
}
function parseOptionalManagedName(raw, command) {
    if (raw === undefined) {
        return undefined;
    }
    try {
        return (0, refs_1.parseScopedName)(raw, 'name');
    }
    catch {
        (0, messages_1.printErrorWithHelp)('The provided name is invalid.', ['Names cannot be empty and cannot contain path separators.'], { command });
        process.exitCode = 1;
        return null;
    }
}
async function browseCreations(options = {}) {
    const kind = parseBrowseKind(options.kind);
    if (!kind) {
        (0, messages_1.printErrorWithHelp)('The --kind value is invalid.', ['Use one of: app, asset, asset-pack, all.'], { command: 'creations browse' });
        process.exitCode = 1;
        return;
    }
    const limit = parsePositiveInteger(options.limit, 'limit', 20);
    if (limit === null) {
        (0, messages_1.printErrorWithHelp)('The --limit value must be a positive integer.', ['Example: --limit 20'], { command: 'creations browse' });
        process.exitCode = 1;
        return;
    }
    const offset = parsePositiveInteger(options.offset, 'offset', 0);
    if (offset === null) {
        (0, messages_1.printErrorWithHelp)('The --offset value must be zero or a positive integer.', ['Example: --offset 20'], { command: 'creations browse' });
        process.exitCode = 1;
        return;
    }
    await (0, commandContext_1.withEnvironment)('creations browse', 'Browsing your creations', async ({ client }) => {
        try {
            const creator = await resolveCreator(client, options.creator, 'creations browse');
            if (!creator) {
                return;
            }
            const usingCurrentCreator = !options.creator || options.creator.trim().toLowerCase() === 'me';
            const items = [];
            let pagination;
            if (kind === 'app') {
                const response = !usingCurrentCreator
                    ? await client.fetchAppsByCreator(creator, { limit, offset })
                    : await client.fetchMyApps({ limit, offset });
                items.push(...(response.apps ?? []).map((item) => ({ kind: 'app', ref: `${item.creatorUsername}/app/${item.name}`, item })));
                pagination = requirePagination(response.pagination, 'creations_browse_app');
            }
            else if (kind === 'asset') {
                const response = await client.listAssetsForCreator(creator, { limit, offset });
                items.push(...(response.assets ?? []).map((item) => ({ kind: 'asset', ref: `${item.creatorUsername}/asset/${item.name}`, item })));
                pagination = response.pagination;
            }
            else if (kind === 'asset-pack') {
                const response = await client.listAssetPacksForCreator(creator, { limit, offset });
                items.push(...(response.packs ?? []).map((item) => ({ kind: 'asset-pack', ref: `${item.creatorUsername}/asset-pack/${item.name}`, item })));
                pagination = response.pagination;
            }
            else {
                const [appsResponse, assetsResponse, packsResponse] = await Promise.all([
                    collectPaginatedItems((pageLimit, pageOffset) => (!usingCurrentCreator
                        ? client.fetchAppsByCreator(creator, { limit: pageLimit, offset: pageOffset })
                        : client.fetchMyApps({ limit: pageLimit, offset: pageOffset }))
                        .then((response) => ({
                        items: response.apps ?? [],
                        pagination: requirePagination(response.pagination, 'creations_browse_all_apps'),
                    }))),
                    collectPaginatedItems((pageLimit, pageOffset) => client.listAssetsForCreator(creator, { limit: pageLimit, offset: pageOffset }).then((response) => ({
                        items: response.assets ?? [],
                        pagination: response.pagination,
                    }))),
                    collectPaginatedItems((pageLimit, pageOffset) => client.listAssetPacksForCreator(creator, { limit: pageLimit, offset: pageOffset }).then((response) => ({
                        items: response.packs ?? [],
                        pagination: response.pagination,
                    }))),
                ]);
                const combined = [
                    ...(appsResponse.items.map((item) => ({ kind: 'app', ref: `${item.creatorUsername}/app/${item.name}`, item }))),
                    ...(assetsResponse.items.map((item) => ({ kind: 'asset', ref: `${item.creatorUsername}/asset/${item.name}`, item }))),
                    ...(packsResponse.items.map((item) => ({ kind: 'asset-pack', ref: `${item.creatorUsername}/asset-pack/${item.name}`, item }))),
                ];
                const sliced = sliceMergedItems(combined, limit, offset);
                items.push(...sliced.items);
                pagination = sliced.pagination;
            }
            if (options.json) {
                (0, output_1.printJson)({
                    items,
                    ...(pagination ? { pagination } : {}),
                });
                return;
            }
            if (items.length === 0) {
                console.log(`No ${kindLabel(kind)} found for @${creator}.`);
                console.log('Next: run "playdrop project create app <name>" or "playdrop ai create <type> <prompt>" to create something new.');
                return;
            }
            if (kind === 'all') {
                console.log(`Creations for @${creator} (apps, then assets, then asset packs):\n`);
            }
            else {
                console.log(`Creations for @${creator}:\n`);
            }
            for (const [index, item] of items.entries()) {
                console.log(`${index + 1}. [${item.kind}] ${item.ref} | ${item.item.displayName || item.item.name}${buildCountsSuffix(item)}`);
            }
            console.log('\nNext: run "playdrop detail <creator>/<kind>/<name>" or a "playdrop creations ..." command to manage one item.');
        }
        catch (error) {
            const handled = (0, errors_1.handleCommandFailure)(error, 'creations browse', 'Creation lookup', {
                apiMessage: (apiError) => ({
                    problem: `Creation lookup failed with status ${apiError.status}.`,
                    suggestions: ['Run "playdrop auth login" and retry.'],
                }),
            });
            if (!handled) {
                throw error;
            }
        }
    });
}
async function updateCreationApp(nameArg, options = {}) {
    const name = parseManagedName(nameArg, 'creations apps update');
    if (!name) {
        return;
    }
    const parsedAppType = options.type ? (0, types_1.parseAppType)(options.type.trim().toUpperCase()) : undefined;
    if (options.type !== undefined && !parsedAppType) {
        (0, messages_1.printErrorWithHelp)('The --type value is invalid.', ['Use one of: game, demo, tool, template.'], { command: 'creations apps update' });
        process.exitCode = 1;
        return;
    }
    const appType = parsedAppType ?? undefined;
    if (!options.displayName && !appType) {
        (0, messages_1.printErrorWithHelp)('At least one update field is required.', ['Use --display-name and/or --type.'], { command: 'creations apps update' });
        process.exitCode = 1;
        return;
    }
    await (0, commandContext_1.withEnvironment)('creations apps update', 'Updating an app', async ({ client }) => {
        try {
            const creator = await resolveCreator(client, options.creator, 'creations apps update');
            if (!creator) {
                return;
            }
            const ref = (0, refs_1.buildScopedRef)(creator, 'app', name);
            const response = await client.updateApp(creator, name, {
                displayName: options.displayName?.trim() || undefined,
                type: appType,
            });
            if (options.json) {
                (0, output_1.printJson)({ ref: ref.ref, item: response.app });
                return;
            }
            (0, output_1.printSuccess)(`Updated ${ref.ref}.`, ['Next: run "playdrop detail ' + ref.ref + '" to review the latest metadata.']);
        }
        catch (error) {
            const handled = (0, errors_1.handleCommandFailure)(error, 'creations apps update', 'App update', {
                apiMessage: (apiError) => ({
                    problem: `App update failed with status ${apiError.status}.`,
                    suggestions: ['Check the app name and your permissions, then retry.'],
                }),
            });
            if (!handled) {
                throw error;
            }
        }
    });
}
async function deleteCreationApp(nameArg, options = {}) {
    const name = parseManagedName(nameArg, 'creations apps delete');
    if (!name) {
        return;
    }
    await (0, commandContext_1.withEnvironment)('creations apps delete', 'Deleting an app', async ({ client }) => {
        try {
            const creator = await resolveCreator(client, options.creator, 'creations apps delete');
            if (!creator) {
                return;
            }
            const ref = (0, refs_1.buildScopedRef)(creator, 'app', name);
            const response = await client.deleteApp(creator, name);
            if (options.json) {
                (0, output_1.printJson)({ success: Boolean(response.success), ref: ref.ref });
                return;
            }
            (0, output_1.printSuccess)(`Deleted ${ref.ref}.`, ['Next: run "playdrop creations browse --kind app" to review your remaining apps.']);
        }
        catch (error) {
            const handled = (0, errors_1.handleCommandFailure)(error, 'creations apps delete', 'App delete', {
                apiMessage: (apiError) => ({
                    problem: `App delete failed with status ${apiError.status}.`,
                    suggestions: ['Check the app name and your permissions, then retry.'],
                }),
            });
            if (!handled) {
                throw error;
            }
        }
    });
}
async function mutateAppVersion(nameArg, versionArg, command, options, mutation, successMessage, next) {
    const name = parseManagedName(nameArg, command);
    if (!name) {
        return;
    }
    const version = parseVersion(versionArg ?? '', command);
    if (!version) {
        return;
    }
    await (0, commandContext_1.withEnvironment)(command, 'Updating an app version', async ({ client }) => {
        try {
            const creator = await resolveCreator(client, options.creator, command);
            if (!creator) {
                return;
            }
            const ref = (0, refs_1.buildScopedRef)(creator, 'app', name);
            const response = await mutation(client, creator, name, version);
            if (options.json) {
                (0, output_1.printJson)({ ref: ref.ref, version, result: response });
                return;
            }
            (0, output_1.printSuccess)(successMessage(ref.ref, version), [next.replace('{ref}', ref.ref)]);
        }
        catch (error) {
            const handled = (0, errors_1.handleCommandFailure)(error, command, 'App version update', {
                apiMessage: (apiError) => ({
                    problem: `App version update failed with status ${apiError.status}.`,
                    suggestions: ['Check the version string and your permissions, then retry.'],
                }),
            });
            if (!handled) {
                throw error;
            }
        }
    });
}
async function setCurrentCreationAppVersion(nameArg, versionArg, options = {}) {
    return mutateAppVersion(nameArg, versionArg, 'creations apps versions set-current', options, (client, creator, name, version) => client.updateAppVersion(creator, name, version, { setAsCurrent: true }), (ref, version) => `${ref} now points to version ${version}.`, 'Next: run "playdrop versions browse {ref}" to inspect version history.');
}
async function publishCreationAppVersion(nameArg, versionArg, options = {}) {
    return mutateAppVersion(nameArg, versionArg, 'creations apps versions publish', options, (client, creator, name, version) => client.updateAppVersion(creator, name, version, { visibility: 'PUBLIC' }), (ref, version) => `Published version ${version} for ${ref}.`, 'Next: run "playdrop versions browse {ref}" to confirm visibility.');
}
async function unpublishCreationAppVersion(nameArg, versionArg, options = {}) {
    return mutateAppVersion(nameArg, versionArg, 'creations apps versions unpublish', options, (client, creator, name, version) => client.updateAppVersion(creator, name, version, { visibility: 'PRIVATE' }), (ref, version) => `Unpublished version ${version} for ${ref}.`, 'Next: run "playdrop versions browse {ref}" to confirm visibility.');
}
async function deleteCreationAppVersion(nameArg, versionArg, options = {}) {
    return mutateAppVersion(nameArg, versionArg, 'creations apps versions delete', options, (client, creator, name, version) => client.deleteAppVersion(creator, name, version), (ref, version) => `Deleted version ${version} from ${ref}.`, 'Next: run "playdrop versions browse {ref}" to review the remaining versions.');
}
async function updateCreationAsset(nameArg, options = {}) {
    const name = parseManagedName(nameArg, 'creations assets update');
    if (!name) {
        return;
    }
    const nextName = parseOptionalManagedName(options.name, 'creations assets update');
    if (nextName === null) {
        return;
    }
    if (options.description !== undefined && options.clearDescription) {
        (0, messages_1.printErrorWithHelp)('Use either --description or --clear-description, not both.', [], { command: 'creations assets update' });
        process.exitCode = 1;
        return;
    }
    if (!nextName && !options.displayName && options.description === undefined && !options.clearDescription) {
        (0, messages_1.printErrorWithHelp)('At least one update field is required.', ['Use --name, --display-name, --description, or --clear-description.'], { command: 'creations assets update' });
        process.exitCode = 1;
        return;
    }
    await (0, commandContext_1.withEnvironment)('creations assets update', 'Updating an asset', async ({ client }) => {
        try {
            const creator = await resolveCreator(client, options.creator, 'creations assets update');
            if (!creator) {
                return;
            }
            const ref = (0, refs_1.buildScopedRef)(creator, 'asset', name);
            const response = await client.updateAsset(creator, name, {
                name: nextName,
                displayName: options.displayName?.trim() || undefined,
                description: options.clearDescription ? null : options.description,
            });
            if (options.json) {
                (0, output_1.printJson)({ ref: ref.ref, item: response.asset });
                return;
            }
            (0, output_1.printSuccess)(`Updated ${ref.ref}.`, ['Next: run "playdrop detail ' + `${response.asset.creatorUsername}/asset/${response.asset.name}` + '" to review the latest metadata.']);
        }
        catch (error) {
            const handled = (0, errors_1.handleCommandFailure)(error, 'creations assets update', 'Asset update', {
                apiMessage: (apiError) => ({
                    problem: `Asset update failed with status ${apiError.status}.`,
                    suggestions: ['Check the asset name and your permissions, then retry.'],
                }),
            });
            if (!handled) {
                throw error;
            }
        }
    });
}
async function deleteCreationAsset(nameArg, options = {}) {
    const name = parseManagedName(nameArg, 'creations assets delete');
    if (!name) {
        return;
    }
    await (0, commandContext_1.withEnvironment)('creations assets delete', 'Deleting an asset', async ({ client }) => {
        try {
            const creator = await resolveCreator(client, options.creator, 'creations assets delete');
            if (!creator) {
                return;
            }
            const ref = (0, refs_1.buildScopedRef)(creator, 'asset', name);
            const response = await client.deleteAsset(creator, name);
            if (options.json) {
                (0, output_1.printJson)({ success: Boolean(response.success), ref: ref.ref });
                return;
            }
            (0, output_1.printSuccess)(`Deleted ${ref.ref}.`, ['Next: run "playdrop creations browse --kind asset" to review your remaining assets.']);
        }
        catch (error) {
            const handled = (0, errors_1.handleCommandFailure)(error, 'creations assets delete', 'Asset delete', {
                apiMessage: (apiError) => ({
                    problem: `Asset delete failed with status ${apiError.status}.`,
                    suggestions: ['Check the asset name and your permissions, then retry.'],
                }),
            });
            if (!handled) {
                throw error;
            }
        }
    });
}
async function mutateAssetVersion(nameArg, revisionArg, command, options, mutation, successMessage, next) {
    const name = parseManagedName(nameArg, command);
    if (!name) {
        return;
    }
    const revision = parseRevision(revisionArg ?? '', command);
    if (revision === null) {
        return;
    }
    await (0, commandContext_1.withEnvironment)(command, 'Updating an asset revision', async ({ client }) => {
        try {
            const creator = await resolveCreator(client, options.creator, command);
            if (!creator) {
                return;
            }
            const ref = (0, refs_1.buildScopedRef)(creator, 'asset', name);
            const response = await mutation(client, creator, name, revision);
            if (options.json) {
                (0, output_1.printJson)({ ref: ref.ref, revision, result: response });
                return;
            }
            (0, output_1.printSuccess)(successMessage(ref.ref, revision), [next.replace('{ref}', ref.ref)]);
        }
        catch (error) {
            const handled = (0, errors_1.handleCommandFailure)(error, command, 'Asset revision update', {
                apiMessage: (apiError) => ({
                    problem: `Asset revision update failed with status ${apiError.status}.`,
                    suggestions: ['Check the revision and your permissions, then retry.'],
                }),
            });
            if (!handled) {
                throw error;
            }
        }
    });
}
async function setCurrentCreationAssetVersion(nameArg, revisionArg, options = {}) {
    return mutateAssetVersion(nameArg, revisionArg, 'creations assets versions set-current', options, (client, creator, name, revision) => client.updateAssetVersion(creator, name, revision, { setAsCurrent: true }), (ref, revision) => `${ref} now points to revision r${revision}.`, 'Next: run "playdrop versions browse {ref}" to inspect revision history.');
}
async function publishCreationAssetVersion(nameArg, revisionArg, options = {}) {
    return mutateAssetVersion(nameArg, revisionArg, 'creations assets versions publish', options, (client, creator, name, revision) => client.updateAssetVersion(creator, name, revision, { visibility: 'PUBLIC' }), (ref, revision) => `Published revision r${revision} for ${ref}.`, 'Next: run "playdrop versions browse {ref}" to confirm visibility.');
}
async function unpublishCreationAssetVersion(nameArg, revisionArg, options = {}) {
    return mutateAssetVersion(nameArg, revisionArg, 'creations assets versions unpublish', options, (client, creator, name, revision) => client.updateAssetVersion(creator, name, revision, { visibility: 'PRIVATE' }), (ref, revision) => `Unpublished revision r${revision} for ${ref}.`, 'Next: run "playdrop versions browse {ref}" to confirm visibility.');
}
async function deleteCreationAssetVersion(nameArg, revisionArg, options = {}) {
    return mutateAssetVersion(nameArg, revisionArg, 'creations assets versions delete', options, (client, creator, name, revision) => client.deleteAssetVersion(creator, name, revision), (ref, revision) => `Deleted revision r${revision} from ${ref}.`, 'Next: run "playdrop versions browse {ref}" to review the remaining revisions.');
}
async function updateCreationAssetPack(nameArg, options = {}) {
    const name = parseManagedName(nameArg, 'creations asset-packs update');
    if (!name) {
        return;
    }
    const nextName = parseOptionalManagedName(options.name, 'creations asset-packs update');
    if (nextName === null) {
        return;
    }
    if (options.description !== undefined && options.clearDescription) {
        (0, messages_1.printErrorWithHelp)('Use either --description or --clear-description, not both.', [], { command: 'creations asset-packs update' });
        process.exitCode = 1;
        return;
    }
    if (options.previewAppVersionId !== undefined && options.clearPreviewAppVersionId) {
        (0, messages_1.printErrorWithHelp)('Use either --preview-app-version-id or --clear-preview-app-version-id, not both.', [], { command: 'creations asset-packs update' });
        process.exitCode = 1;
        return;
    }
    const previewAppVersionId = options.previewAppVersionId !== undefined
        ? parsePositiveInteger(options.previewAppVersionId, 'preview app version id', 0)
        : null;
    if (options.previewAppVersionId !== undefined && (previewAppVersionId === null || previewAppVersionId <= 0)) {
        (0, messages_1.printErrorWithHelp)('Preview app version id must be a positive integer.', [], { command: 'creations asset-packs update' });
        process.exitCode = 1;
        return;
    }
    if (!nextName && !options.displayName && options.description === undefined && !options.clearDescription && previewAppVersionId === null && !options.clearPreviewAppVersionId) {
        (0, messages_1.printErrorWithHelp)('At least one update field is required.', ['Use --name, --display-name, --description, --preview-app-version-id, or a clear flag.'], { command: 'creations asset-packs update' });
        process.exitCode = 1;
        return;
    }
    await (0, commandContext_1.withEnvironment)('creations asset-packs update', 'Updating an asset pack', async ({ client }) => {
        try {
            const creator = await resolveCreator(client, options.creator, 'creations asset-packs update');
            if (!creator) {
                return;
            }
            const ref = (0, refs_1.buildScopedRef)(creator, 'asset-pack', name);
            const response = await client.updateAssetPack(creator, name, {
                name: nextName,
                displayName: options.displayName?.trim() || undefined,
                description: options.clearDescription ? null : options.description,
                previewAppVersionId: options.clearPreviewAppVersionId ? null : previewAppVersionId ?? undefined,
            });
            if (options.json) {
                (0, output_1.printJson)({ ref: ref.ref, item: response.pack });
                return;
            }
            (0, output_1.printSuccess)(`Updated ${ref.ref}.`, ['Next: run "playdrop detail ' + `${response.pack.creatorUsername}/asset-pack/${response.pack.name}` + '" to review the latest metadata.']);
        }
        catch (error) {
            const handled = (0, errors_1.handleCommandFailure)(error, 'creations asset-packs update', 'Asset pack update', {
                apiMessage: (apiError) => ({
                    problem: `Asset pack update failed with status ${apiError.status}.`,
                    suggestions: ['Check the asset pack name and your permissions, then retry.'],
                }),
            });
            if (!handled) {
                throw error;
            }
        }
    });
}
async function deleteCreationAssetPack(nameArg, options = {}) {
    const name = parseManagedName(nameArg, 'creations asset-packs delete');
    if (!name) {
        return;
    }
    await (0, commandContext_1.withEnvironment)('creations asset-packs delete', 'Deleting an asset pack', async ({ client }) => {
        try {
            const creator = await resolveCreator(client, options.creator, 'creations asset-packs delete');
            if (!creator) {
                return;
            }
            const ref = (0, refs_1.buildScopedRef)(creator, 'asset-pack', name);
            const response = await client.deleteAssetPack(creator, name);
            if (options.json) {
                (0, output_1.printJson)({ success: Boolean(response.success), ref: ref.ref });
                return;
            }
            (0, output_1.printSuccess)(`Deleted ${ref.ref}.`, ['Next: run "playdrop creations browse --kind asset-pack" to review your remaining asset packs.']);
        }
        catch (error) {
            const handled = (0, errors_1.handleCommandFailure)(error, 'creations asset-packs delete', 'Asset pack delete', {
                apiMessage: (apiError) => ({
                    problem: `Asset pack delete failed with status ${apiError.status}.`,
                    suggestions: ['Check the asset pack name and your permissions, then retry.'],
                }),
            });
            if (!handled) {
                throw error;
            }
        }
    });
}
async function mutateAssetPackVersion(nameArg, versionArg, command, options, mutation, successMessage, next) {
    const name = parseManagedName(nameArg, command);
    if (!name) {
        return;
    }
    const version = parseVersion(versionArg ?? '', command);
    if (!version) {
        return;
    }
    await (0, commandContext_1.withEnvironment)(command, 'Updating an asset pack version', async ({ client }) => {
        try {
            const creator = await resolveCreator(client, options.creator, command);
            if (!creator) {
                return;
            }
            const ref = (0, refs_1.buildScopedRef)(creator, 'asset-pack', name);
            const response = await mutation(client, creator, name, version);
            if (options.json) {
                (0, output_1.printJson)({ ref: ref.ref, version, result: response });
                return;
            }
            (0, output_1.printSuccess)(successMessage(ref.ref, version), [next.replace('{ref}', ref.ref)]);
        }
        catch (error) {
            const handled = (0, errors_1.handleCommandFailure)(error, command, 'Asset pack version update', {
                apiMessage: (apiError) => ({
                    problem: `Asset pack version update failed with status ${apiError.status}.`,
                    suggestions: ['Check the version string and your permissions, then retry.'],
                }),
            });
            if (!handled) {
                throw error;
            }
        }
    });
}
async function setCurrentCreationAssetPackVersion(nameArg, versionArg, options = {}) {
    return mutateAssetPackVersion(nameArg, versionArg, 'creations asset-packs versions set-current', options, (client, creator, name, version) => client.updateAssetPackVersion(creator, name, version, { setAsCurrent: true }), (ref, version) => `${ref} now points to version ${version}.`, 'Next: run "playdrop versions browse {ref}" to inspect version history.');
}
async function publishCreationAssetPackVersion(nameArg, versionArg, options = {}) {
    return mutateAssetPackVersion(nameArg, versionArg, 'creations asset-packs versions publish', options, (client, creator, name, version) => client.updateAssetPackVersion(creator, name, version, { visibility: 'PUBLIC' }), (ref, version) => `Published version ${version} for ${ref}.`, 'Next: run "playdrop versions browse {ref}" to confirm visibility.');
}
async function unpublishCreationAssetPackVersion(nameArg, versionArg, options = {}) {
    return mutateAssetPackVersion(nameArg, versionArg, 'creations asset-packs versions unpublish', options, (client, creator, name, version) => client.updateAssetPackVersion(creator, name, version, { visibility: 'PRIVATE' }), (ref, version) => `Unpublished version ${version} for ${ref}.`, 'Next: run "playdrop versions browse {ref}" to confirm visibility.');
}
async function deleteCreationAssetPackVersion(nameArg, versionArg, options = {}) {
    return mutateAssetPackVersion(nameArg, versionArg, 'creations asset-packs versions delete', options, (client, creator, name, version) => client.deleteAssetPackVersion(creator, name, version), (ref, version) => `Deleted version ${version} from ${ref}.`, 'Next: run "playdrop versions browse {ref}" to review the remaining versions.');
}
