// app/api/telegram/lib/bot-handlers.ts
import { bot, memory, getLiterals } from './config'; // Import getLiterals function
import { handleConsultingCallbacks, setupConsultingHandler } from './consulting-handler';
import { processMessage } from './message-processor';
import { BotState, handleShopCallbacks, handleTransactionHashInput, setupShopHandler } from './shop-handler';
import { handleTicketCallbacks, handleTicketInput, setupTicketHandler, TicketState } from './ticket-handler';
import { prisma } from '@/lib/prisma';

export async function setupBotHandlers() {


    if (process.env.NEXT_PUBLIC_PANEL_TEMPLATE == 'prop_firms') {
        await setupShopHandler();
        await setupConsultingHandler();
    }

    await setupTicketHandler();



    bot.use(async (ctx, next) => {
        if (ctx.message && 'text' in ctx.message) {
            console.log(`Received message from ${ctx.from?.id}: ${ctx.message.text}`);
        }
        await next();
    });
    bot.start(async (ctx) => {
        if (!ctx.from) return;
        if (!memory) {
            console.error("Memory not initialized during /start");
            await ctx.reply("سیستم در حال آماده سازی است، لطفا لحظاتی دیگر مجدد تلاش کنید.");
            return;
        }
        const user = await memory.getOrCreateUser(ctx.from);
        await memory.startNewConversation(ctx.chat.id, user.id);

        const currentLiterals = await getLiterals(); // Fetch fresh literals
        const welcomeMessage = currentLiterals.welcomeText || "به ربات خوش آمدید! (پیش فرض)";

        await memory.saveMessage(ctx.chat.id, 'assistant', welcomeMessage, ctx.from);
        await ctx.reply(welcomeMessage);
    });
    bot.command('test', async (ctx) => {
        if (!ctx.from) return;
        ctx.reply('Test 3');
        return;
    });
    bot.command('new', async (ctx) => {
        if (!ctx.from) return;
        if (!memory) {
            console.error("Memory not initialized during /new");
            await ctx.reply("سیستم در حال آماده سازی است، لطفا لحظاتی دیگر مجدد تلاش کنید.");
            return;
        }
        const user = await memory.getOrCreateUser(ctx.from);
        await memory.startNewConversation(ctx.chat.id, user.id);
        const message = 'مکالمه جدید شروع شد. چگونه می‌توانم به شما کمک کنم؟';

        await memory.saveMessage(ctx.chat.id, 'assistant', message, ctx.from);
        await ctx.reply(message);
    });

    bot.on('callback_query', async (ctx) => {
        if (!ctx.from || !ctx.callbackQuery) return;
        if ('data' in ctx.callbackQuery && typeof ctx.callbackQuery.data === 'string') {
            try {
                const data = ctx.callbackQuery.data;
                console.log(data);
                const user = await memory.getOrCreateUser(ctx.from);
                if (data.startsWith('shop_')) {
                    if (process.env.NEXT_PUBLIC_PANEL_TEMPLATE == 'prop_firms') {
                        await handleShopCallbacks(ctx, data, user);
                    }
                }
                else if (data === 'request_admin' || data === 'switch_to_ai' || data === 'exit_consulting') {
                    if (process.env.NEXT_PUBLIC_PANEL_TEMPLATE == 'prop_firms') {
                        await handleConsultingCallbacks(ctx, data, user);
                    }
                }
                else if (data.startsWith('ticket_')) {
                    await handleTicketCallbacks(ctx, data, user);
                }
            } catch (error) {
                console.error('Error in callback query:', error);
                await ctx.answerCbQuery('خطایی رخ داد. لطفاً بعداً دوباره تلاش کنید.');
            }
        }
    });

    bot.on('text', async (ctx) => {
        if (!ctx.from) return;
        const messageText = (ctx.message as { text: string }).text;
        const currentLiterals = await getLiterals();
        if (currentLiterals.commands && Array.isArray(currentLiterals.commands)) {
            const matchedCommand = currentLiterals.commands.find((command: any) => command.command === messageText);
            if (matchedCommand) {
                if (!memory) {
                    console.error(`Memory not initialized during dynamic command ${messageText}`);
                    await ctx.reply("سیستم در حال آماده سازی است، لطفا لحظاتی دیگر مجدد تلاش کنید.");
                    return;
                }
                console.log(`Handling dynamic command: ${messageText}`);
                await memory.saveMessage(ctx.chat.id, 'assistant', matchedCommand.value, ctx.from);
                await ctx.reply(matchedCommand.value);
                return;
            }
        }
        const user = await memory.getOrCreateUser(ctx.from);
        const userState = await prisma.userBotState.findFirst({
            where: { telegramUserId: user.id }
        });

        if (userState?.state === BotState.ENTER_TRANSACTION_HASH) {
            await handleTransactionHashInput(ctx, user, userState);
            return;
        }
        else if (userState?.state === TicketState.CREATE_TICKET) {
            await handleTicketInput(ctx, messageText, user);
            return;
        }

        await processMessage(ctx, messageText, currentLiterals);
    });

}


