"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.showAdsEarnings = showAdsEarnings;
exports.showAdsReport = showAdsReport;
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");
function parsePositiveInteger(raw, command) {
    if (raw === undefined) {
        return 30;
    }
    const parsed = typeof raw === 'number' ? raw : Number.parseInt(String(raw), 10);
    if (!Number.isInteger(parsed) || parsed <= 0) {
        (0, messages_1.printErrorWithHelp)('The --days value must be a positive integer.', ['Example: --days 30'], { command });
        process.exitCode = 1;
        return null;
    }
    return parsed;
}
async function resolveOptionalAppId(client, rawAppRef) {
    if (!rawAppRef) {
        return undefined;
    }
    const ref = (0, refs_1.parseContentRef)(rawAppRef);
    if (ref.kind !== 'app') {
        throw new Error('invalid_app_ref');
    }
    const detail = await client.fetchAppBySlug(ref.creator, ref.name);
    return Number(detail.app.id);
}
async function showAdsEarnings(options = {}) {
    const days = parsePositiveInteger(options.days, 'ads earnings');
    if (days === null) {
        return;
    }
    await (0, commandContext_1.withEnvironment)('ads earnings', 'Checking creator ad earnings', async ({ client }) => {
        try {
            const appId = await resolveOptionalAppId(client, options.app);
            const response = await client.fetchCreatorEarnings({
                days,
                ...(typeof appId === 'number' && appId > 0 ? { appId } : {}),
            });
            if (options.json) {
                (0, output_1.printJson)(response);
                return;
            }
            const aggregateRows = new Map();
            for (const day of response.days) {
                for (const row of day.apps) {
                    const key = `${row.appId}:${row.format}`;
                    const current = aggregateRows.get(key) ?? {
                        appName: row.appName,
                        format: row.format,
                        amount: 0,
                        servedCount: 0,
                        creditedCount: 0,
                    };
                    current.amount += row.amount;
                    current.servedCount += row.servedCount;
                    current.creditedCount += row.creditedCount;
                    aggregateRows.set(key, current);
                }
            }
            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}`);
            if (aggregateRows.size === 0) {
                console.log('\nNo ad earnings found for the selected window.');
                return;
            }
            console.log('\nBy app and format:\n');
            for (const row of aggregateRows.values()) {
                console.log(`${row.appName} | ${row.format} | earnings ${row.amount} | served ${row.servedCount} | credited ${row.creditedCount}`);
            }
        }
        catch (error) {
            const handled = (0, errors_1.handleCommandFailure)(error, 'ads earnings', 'Ad earnings lookup', {
                apiMessage: (apiError) => ({
                    problem: `Ad earnings lookup failed with status ${apiError.status}.`,
                    suggestions: ['Run "playdrop auth login" and retry.'],
                }),
            });
            if (!handled) {
                throw error;
            }
        }
    });
}
async function showAdsReport(options = {}) {
    const days = parsePositiveInteger(options.days, 'ads report');
    if (days === null) {
        return;
    }
    await (0, commandContext_1.withEnvironment)('ads report', 'Checking creator ad report', async ({ client }) => {
        try {
            const appId = await resolveOptionalAppId(client, options.app);
            const response = await client.fetchCreatorEarnings({
                days,
                ...(typeof appId === 'number' && appId > 0 ? { appId } : {}),
            });
            if (options.json) {
                (0, output_1.printJson)(response);
                return;
            }
            console.log('Daily ad report:\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' : ''}`);
            }
        }
        catch (error) {
            const handled = (0, errors_1.handleCommandFailure)(error, 'ads report', 'Ad report lookup', {
                apiMessage: (apiError) => ({
                    problem: `Ad report lookup failed with status ${apiError.status}.`,
                    suggestions: ['Run "playdrop auth login" and retry.'],
                }),
            });
            if (!handled) {
                throw error;
            }
        }
    });
}
