// app/api/telegram/services/transaction-processor.ts
import { TransactionStatus } from '@/lib/generated/prisma';
import { BlockchainChecker } from './blockchain-checker';
import { bot } from '../lib/config';

import { prisma } from '@/lib/prisma';
const checker = new BlockchainChecker();

export class TransactionProcessor {
    private checkInterval: number = 30000; // 30 ثانیه
    private maxAttempts: number = 20; // حداکثر 10 دقیقه بررسی
    private activeChecks: Map<string, NodeJS.Timeout> = new Map();

    // شروع بررسی یک تراکنش
    async startProcessing(transactionId: string) {
        // جلوگیری از بررسی دوباره
        if (this.activeChecks.has(transactionId)) {
            return;
        }

        let attempts = 0;

        const checkTransaction = async () => {
            attempts++;

            try {
                // دریافت اطلاعات تراکنش
                const transaction = await prisma.userTransaction.findUnique({
                    where: { id: transactionId },
                    include: {
                        telegramUser: true
                    }
                });

                if (!transaction || transaction.status !== 'PENDING') {
                    this.stopProcessing(transactionId);
                    return;
                }

                // دریافت آدرس کیف پول مقصد
                const wallet = await prisma.wallet.findFirst({
                    where: { network: transaction.network },
                    orderBy: { id: 'asc' }
                });

                if (!wallet) {
                    await this.updateTransactionStatus(
                        transaction.id,
                        'FAILED',
                        'Wallet address not found'
                    );
                    this.stopProcessing(transactionId);
                    return;
                }

                // بررسی تراکنش در بلاکچین
                const result = await checker.checkTransaction(
                    transaction.transactionHash,
                    transaction.network
                );

                if (result.success && result.toAddress && result.amount) {
                    // بررسی آدرس مقصد
                    if (!checker.isValidRecipient(result.toAddress, wallet.address)) {
                        await this.updateTransactionStatus(
                            transaction.id,
                            'FAILED',
                            'Transfer to wrong address'
                        );
                        // ارسال پیام خطا به کاربر
                        return;
                    }

                    // تراکنش موفق
                    await this.handleSuccessfulTransaction(
                        transaction.id,
                        transaction.telegramUserId,
                        result.amount,
                        transaction.telegramUser.telegramId
                    );
                } else if (result.error && !result.error.includes('Waiting for confirmations')) {
                    // خطای دائمی
                    await this.updateTransactionStatus(
                        transaction.id,
                        'FAILED',
                        result.error
                    );

                    // اطلاع به کاربر
                    await bot.telegram.sendMessage(
                        transaction.telegramUser.telegramId,
                        `❌ تراکنش شما رد شد\n\n` +
                        `🔗 هش: \`${transaction.transactionHash}\`\n` +
                        `📝 دلیل: ${result.error}\n\n` +
                        `در صورت داشتن سوال با پشتیبانی تماس بگیرید.`,
                        { parse_mode: 'Markdown' }
                    );

                    this.stopProcessing(transactionId);

                } else if (attempts >= this.maxAttempts) {
                    // تایم‌اوت
                    await this.updateTransactionStatus(
                        transaction.id,
                        'FAILED',
                        'Transaction timeout'
                    );

                    await bot.telegram.sendMessage(
                        transaction.telegramUser.telegramId,
                        `⏱ زمان بررسی تراکنش شما به پایان رسید\n\n` +
                        `🔗 هش: \`${transaction.transactionHash}\`\n\n` +
                        `لطفاً با پشتیبانی تماس بگیرید.`,
                        { parse_mode: 'Markdown' }
                    );

                    this.stopProcessing(transactionId);
                }
                // در غیر این صورت منتظر می‌مانیم

            } catch (error) {
                console.error('Transaction check error:', error);

                if (attempts >= this.maxAttempts) {
                    await this.updateTransactionStatus(
                        transactionId,
                        'FAILED',
                        'Check process failed'
                    );
                    this.stopProcessing(transactionId);
                }
            }
        };

        // اولین بررسی فوری
        await checkTransaction();

        // تنظیم بررسی‌های دوره‌ای
        const intervalId = setInterval(checkTransaction, this.checkInterval);
        this.activeChecks.set(transactionId, intervalId);
    }

    // توقف بررسی
    private stopProcessing(transactionId: string) {
        const intervalId = this.activeChecks.get(transactionId);
        if (intervalId) {
            clearInterval(intervalId);
            this.activeChecks.delete(transactionId);
        }
    }

    // مدیریت تراکنش موفق
    private async handleSuccessfulTransaction(
        transactionId: string,
        telegramUserId: string,
        amount: number,
        telegramId: string
    ) {
        await prisma.$transaction(async (tx) => {
            // به‌روزرسانی وضعیت تراکنش
            await tx.userTransaction.update({
                where: { id: transactionId },
                data: {
                    status: 'SUCCESS',
                    value: amount
                }
            });

            // افزایش موجودی کاربر
            await tx.telegramUser.update({
                where: { id: telegramUserId },
                data: {
                    balance: {
                        increment: amount
                    }
                }
            });
        });

        // اطلاع به کاربر
        await bot.telegram.sendMessage(
            telegramId,
            `✅ تراکنش شما با موفقیت تأیید شد!\n\n` +
            `💰 مبلغ: ${amount} تتر\n` +
            `💵 به موجودی شما اضافه شد\n\n` +
            `برای مشاهده موجودی جدید از دستور /shop استفاده کنید.`,
            { parse_mode: 'Markdown' }
        );
    }

    // به‌روزرسانی وضعیت تراکنش
    private async updateTransactionStatus(
        transactionId: string,
        status: TransactionStatus,
        error?: string
    ) {
        await prisma.userTransaction.update({
            where: { id: transactionId },
            data: {
                status,
                updatedAt: new Date()
            }
        });
    }

    // بررسی تمام تراکنش‌های معلق (برای راه‌اندازی مجدد سرور)
    async checkPendingTransactions() {
        const pendingTransactions = await prisma.userTransaction.findMany({
            where: { status: 'PENDING' },
            select: { id: true }
        });

        for (const tx of pendingTransactions) {
            await this.startProcessing(tx.id);
        }
    }
}

// ایجاد یک instance singleton
export const transactionProcessor = new TransactionProcessor();