"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchRegisteredAppShell = fetchRegisteredAppShell;
exports.ensureRegisteredHostedAppShell = ensureRegisteredHostedAppShell;
const types_1 = require("@playdrop/types");
function resolveRegistrationDisplayName(task) {
    const displayName = typeof task.displayName === 'string' ? task.displayName.trim() : '';
    return displayName || task.name;
}
async function fetchRegisteredAppShell(client, creatorUsername, appName) {
    try {
        const response = await client.fetchAppBySlug(creatorUsername, appName);
        return response?.app ?? null;
    }
    catch (error) {
        if (error instanceof types_1.ApiError && error.status === 404) {
            return null;
        }
        throw error;
    }
}
async function ensureRegisteredHostedAppShell(input) {
    let app = await fetchRegisteredAppShell(input.client, input.creatorUsername, input.task.name);
    let created = false;
    const displayName = resolveRegistrationDisplayName(input.task);
    if (!app) {
        const createdResponse = await input.client.createApp(input.creatorUsername, {
            name: input.task.name,
            displayName,
        });
        app = createdResponse.app;
        created = true;
    }
    if (!app) {
        throw new Error(`App ${input.creatorUsername}/${input.task.name} could not be registered on PlayDrop.`);
    }
    const updateRequest = {};
    if (app.displayName !== displayName) {
        updateRequest.displayName = displayName;
    }
    if (input.task.type && app.type !== input.task.type) {
        updateRequest.type = input.task.type;
    }
    if (Object.keys(updateRequest).length > 0) {
        const updated = await input.client.updateApp(input.creatorUsername, input.task.name, updateRequest);
        app = updated.app;
    }
    return { app, created };
}
