"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.showCreditBalance = showCreditBalance;
exports.browseCreditTransactions = browseCreditTransactions;
exports.showCreatorEarnings = showCreatorEarnings;
const commandContext_1 = require("../commandContext");
const errors_1 = require("../errors");
const messages_1 = require("../messages");
const output_1 = require("../output");
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;
}
function formatTransactionTitle(transaction) {
    if (transaction.type === 'AD_PAYOUT') {
        const appName = typeof transaction.metadata?.appName === 'string' ? transaction.metadata.appName : transaction.displayName;
        const adFormat = typeof transaction.metadata?.adFormat === 'string' ? transaction.metadata.adFormat : null;
        const dateUtc = typeof transaction.metadata?.dateUtc === 'string' ? transaction.metadata.dateUtc : null;
        return [appName, adFormat, dateUtc].filter(Boolean).join(' | ');
    }
    if (transaction.type === 'BOOST_PURCHASE') {
        const units = typeof transaction.metadata?.units === 'number' ? transaction.metadata.units : null;
        return units ? `${transaction.displayName} | ${units} units` : transaction.displayName;
    }
    return transaction.displayName;
}
async function showCreditBalance(options = {}) {
    await (0, commandContext_1.withEnvironment)('credits balance', 'Checking your credit balance', async ({ client }) => {
        try {
            const response = await client.me();
            const balance = response.user?.creditBalance ?? 0;
            if (options.json) {
                (0, output_1.printJson)({ balance });
                return;
            }
            (0, output_1.printSuccess)(`Credit balance: ${balance}`, ['Next: run "playdrop credits transactions" to review recent credit activity.']);
        }
        catch (error) {
            const handled = (0, errors_1.handleCommandFailure)(error, 'credits balance', 'Credit balance lookup', {
                apiMessage: (apiError) => ({
                    problem: `Credit balance lookup failed with status ${apiError.status}.`,
                    suggestions: ['Run "playdrop auth login" and retry.'],
                }),
            });
            if (!handled) {
                throw error;
            }
        }
    });
}
async function browseCreditTransactions(options = {}) {
    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: 'credits transactions' });
        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: 'credits transactions' });
        process.exitCode = 1;
        return;
    }
    await (0, commandContext_1.withEnvironment)('credits transactions', 'Checking your credit history', async ({ client }) => {
        try {
            const response = await client.fetchCreditTransactions({ limit, offset });
            const transactions = response.transactions ?? [];
            if (options.json) {
                (0, output_1.printJson)({ transactions });
                return;
            }
            if (transactions.length === 0) {
                console.log('No credit transactions found.');
                console.log('Next: run "playdrop credits balance" to confirm your current balance.');
                return;
            }
            console.log('Credit transactions:\n');
            for (const transaction of transactions) {
                console.log(`#${transaction.id} | ${transaction.kind.toLowerCase()} | ${transaction.amount} | ${transaction.status.toLowerCase()} | ${(0, output_1.formatTimestamp)(transaction.createdAt)}`);
                console.log(`  ${formatTransactionTitle(transaction)}`);
            }
            console.log('\nNext: run "playdrop credits balance" to confirm your latest balance.');
        }
        catch (error) {
            const handled = (0, errors_1.handleCommandFailure)(error, 'credits transactions', 'Credit transaction lookup', {
                apiMessage: (apiError) => ({
                    problem: `Credit transaction lookup failed with status ${apiError.status}.`,
                    suggestions: ['Run "playdrop auth login" and retry.'],
                }),
            });
            if (!handled) {
                throw error;
            }
        }
    });
}
async function showCreatorEarnings(options = {}) {
    const days = parsePositiveInteger(options.days, 'days', 30);
    if (days === null) {
        (0, messages_1.printErrorWithHelp)('The --days value must be a positive integer.', ['Example: --days 30'], { command: 'credits earnings' });
        process.exitCode = 1;
        return;
    }
    const appId = options.appId === undefined ? undefined : parsePositiveInteger(options.appId, 'appId', 0);
    if (options.appId !== undefined && appId === null) {
        (0, messages_1.printErrorWithHelp)('The --app-id value must be a positive integer.', ['Example: --app-id 123'], { command: 'credits earnings' });
        process.exitCode = 1;
        return;
    }
    await (0, commandContext_1.withEnvironment)('credits earnings', 'Checking creator ad earnings', async ({ client }) => {
        const response = await client.fetchCreatorEarnings({
            days,
            ...(appId && appId > 0 ? { appId } : {}),
        });
        if (options.json) {
            (0, output_1.printJson)(response);
            return;
        }
        console.log(`Today provisional: ${response.summary.provisionalToday}`);
        console.log(`Last 7 days settled: ${response.summary.settledLast7Days}`);
        console.log(`Last 30 days settled: ${response.summary.settledLast30Days}`);
        console.log(`Last 30 days boost spend: ${response.summary.boostSpendLast30Days}`);
        console.log('\nDaily rows:\n');
        for (const row of response.days) {
            console.log(`${row.dateUtc} | total ${row.totalAmount} | interstitial ${row.interstitialAmount} | rewarded ${row.rewardedAmount} | served ${row.servedCount} | credited ${row.creditedCount}${row.provisional ? ' | provisional' : ''}`);
        }
    });
}
