"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StarsManager = void 0;
const uuid_1 = require("uuid");
const index_js_1 = require("../../utils/index.js");
const log = (0, index_js_1.createModuleLogger)('stars-manager');
class StarsManager {
    dataStore;
    constructor(dataStore) {
        this.dataStore = dataStore;
    }
    async handlePreCheckout(characterId, query, botClient) {
        log.info({ characterId, queryId: query.id, userId: query.from.id }, 'Handling pre-checkout query');
        await this.createTransaction({
            characterId,
            telegramUserId: query.from.id,
            type: 'payment',
            starCount: query.total_amount,
            status: 'pending',
        });
        try {
            await botClient.answerPreCheckoutQuery(query.id, true);
            log.info({ characterId, queryId: query.id }, 'Pre-checkout query approved');
        }
        catch (err) {
            log.error({ characterId, queryId: query.id, err }, 'Failed to answer pre-checkout query');
            throw err;
        }
    }
    async handleSuccessfulPayment(characterId, payment, telegramUserId, botClient) {
        log.info({ characterId, userId: telegramUserId, amount: payment.total_amount }, 'Handling successful payment');
        const imageId = this.parseImageIdFromPayload(payment.invoice_payload);
        const tx = await this.createTransaction({
            characterId,
            telegramUserId,
            type: 'payment',
            starCount: payment.total_amount,
            status: 'completed',
            telegramPaymentId: payment.telegram_payment_charge_id,
            imageId: imageId ?? undefined,
        });
        if (imageId) {
            try {
                await botClient.sendPaidMedia({
                    chat_id: telegramUserId,
                    star_count: payment.total_amount,
                    media: [{ type: 'photo', media: imageId }],
                });
                log.info({ characterId, imageId, userId: telegramUserId }, 'Paid media sent');
            }
            catch (err) {
                log.error({ characterId, imageId, err }, 'Failed to send paid media');
            }
        }
        log.info({ characterId, txId: tx.id }, 'Successful payment processed');
        return tx;
    }
    async handleStarReaction(characterId, userId, starCount) {
        log.info({ characterId, userId, starCount }, 'Handling star reaction');
        return this.createTransaction({
            characterId,
            telegramUserId: userId,
            type: 'reaction',
            starCount,
            status: 'completed',
        });
    }
    async publishPaidMedia(characterId, channelId, imageId, starCount, botClient, caption) {
        log.info({ characterId, channelId, imageId, starCount }, 'Publishing paid media to VIP channel');
        await botClient.sendPaidMedia({
            chat_id: Number(channelId) || channelId,
            star_count: starCount,
            media: [{ type: 'photo', media: imageId }],
            caption,
        });
        log.info({ characterId, channelId }, 'Paid media published to channel');
    }
    /**
     * Sends a Stars invoice to a user in DM for purchasing premium content.
     */
    async sendContentInvoice(characterId, userId, botClient, options) {
        const payload = JSON.stringify({
            characterId,
            imageId: options.imageId,
            type: 'premium_content',
        });
        await botClient.sendInvoice({
            chat_id: userId,
            title: options.title,
            description: options.description,
            payload,
            currency: 'XTR', // Telegram Stars currency
            prices: [{ label: options.title, amount: options.starCount }],
        });
        log.info({ characterId, userId, starCount: options.starCount }, 'Stars invoice sent to user DM');
    }
    async getTransactions(characterId, options) {
        let transactions = await this.dataStore.getStarsTransactions(characterId);
        if (options?.type) {
            transactions = transactions.filter((t) => t.type === options.type);
        }
        if (options?.status) {
            transactions = transactions.filter((t) => t.status === options.status);
        }
        transactions.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
        const offset = options?.offset ?? 0;
        const limit = options?.limit ?? transactions.length;
        return transactions.slice(offset, offset + limit);
    }
    async getRevenue(characterId, period) {
        const transactions = await this.dataStore.getStarsTransactions(characterId);
        const completed = transactions.filter((t) => t.status === 'completed');
        let filtered = completed;
        if (period) {
            const now = new Date();
            let cutoff;
            switch (period) {
                case 'daily':
                    cutoff = new Date(now.getTime() - 24 * 60 * 60 * 1000);
                    break;
                case 'weekly':
                    cutoff = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
                    break;
                case 'monthly':
                    cutoff = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
                    break;
            }
            filtered = completed.filter((t) => new Date(t.createdAt) >= cutoff);
        }
        const byType = { payment: 0, reaction: 0 };
        let totalStars = 0;
        for (const t of filtered) {
            totalStars += t.starCount;
            byType[t.type] += t.starCount;
        }
        return { totalStars, totalTransactions: filtered.length, byType };
    }
    async createTransaction(data) {
        const tx = {
            id: (0, uuid_1.v4)(),
            characterId: data.characterId,
            telegramUserId: data.telegramUserId,
            type: data.type,
            starCount: data.starCount,
            imageId: data.imageId,
            channelId: data.channelId,
            status: data.status ?? 'pending',
            telegramPaymentId: data.telegramPaymentId,
            createdAt: new Date().toISOString(),
        };
        await this.dataStore.saveStarsTransaction(tx);
        log.info({ txId: tx.id, characterId: tx.characterId, type: tx.type }, 'Transaction created');
        return tx;
    }
    parseImageIdFromPayload(payload) {
        try {
            const parsed = JSON.parse(payload);
            return parsed.imageId ?? undefined;
        }
        catch {
            if (payload.startsWith('img_'))
                return payload;
            return undefined;
        }
    }
}
exports.StarsManager = StarsManager;
//# sourceMappingURL=stars-manager.js.map