// app/api/users/[userId]/conversations/[conversationId]/messages/route.ts
import { NextResponse } from "next/server";
;
import { Telegraf } from 'telegraf';

import { prisma } from '@/lib/prisma';
const bot = new Telegraf(process.env.TELEGRAM_BOT_TOKEN as string);

export async function POST(
    request: Request,
    { params }: { params: Promise<{ userId: string; conversationId: string }> }
  ) {
    // تصحیح نحوه دریافت پارامترها
    const { userId, conversationId } = await params;
    
    try {
        const body = await request.json();
        const { content, role, sendToTelegram = true } = body; // پیش‌فرض true گذاشتم برای آزمایش

        if (!content || !role) {
            return NextResponse.json({ error: "محتوا و نقش پیام الزامی است" }, { status: 400 });
        }

        // با جزئیات بیشتری مکالمه را دریافت کنیم
        const conversation = await prisma.conversation.findUnique({
            where: {
                id: conversationId,
                telegramUserId: userId,
            },
            include: {
                telegramUser: true
            }
        });

        if (!conversation) {
            return NextResponse.json({ error: "مکالمه یافت نشد" }, { status: 404 });
        }

        // لاگ کردن اطلاعات مکالمه برای دیباگ
        console.log("Conversation data:", JSON.stringify({
            id: conversation.id,
            telegramChatId: conversation.telegramChatId,
            userId: conversation.telegramUserId
        }));

        // پیام را در دیتابیس ذخیره کنیم
        const message = await prisma.message.create({
            data: {
                content,
                role,
                conversationId,
                isRead: role === "assistant", // Messages from assistant are already read
            },
        });

        // ارسال پیام به تلگرام
        if (sendToTelegram) {
            try {
                // بررسی وجود telegramChatId
                if (!conversation.telegramChatId) {
                    console.error("telegramChatId not found for conversation:", conversationId);
                    return NextResponse.json({ 
                        message, 
                        warning: "پیام در دیتابیس ذخیره شد اما telegramChatId برای ارسال به تلگرام یافت نشد" 
                    });
                }

                // قبل از ارسال لاگ بگیریم
                console.log(`Attempting to send message to Telegram chat ID: ${conversation.telegramChatId}`);
                
                // ارسال پیام به تلگرام با await صریح
                const telegramResult = await bot.telegram.sendMessage(
                    conversation.telegramChatId, 
                    content
                );
                
                console.log("Telegram API response:", telegramResult);
                
                // ارسال موفقیت‌آمیز
                return NextResponse.json({ 
                    message, 
                    telegramSent: true,
                    telegramResult 
                });
            } catch (telegramError) {
                console.error("[TELEGRAM_SEND_ERROR]", telegramError);
                
                // بازگرداندن پیام همراه با خطای تلگرام
                return NextResponse.json({ 
                    message, 
                    telegramSent: false, 
                    telegramError: (telegramError as Error).message 
                });
            }
        }

        return NextResponse.json({ message });
    } catch (error) {
        console.error("[MESSAGE_POST]", error);
        return NextResponse.json({ error: "خطای سرور داخلی" }, { status: 500 });
    }
}