import { Controller, Get, Post, Query, Body, Req, Res, All, Logger, Inject } from "@nestjs/common";
import { Request, Response } from "express";
import { PrismaService } from './common/services/prisma.service';
import { Telegraf } from "telegraf";
@Controller('')
export class AppController {
    constructor(
        private prisma: PrismaService,
        @Inject('TELEGRAF_BOT') private bot: Telegraf
    ) { }

    @Get('offer')
    async sendOffer() {
        const users = await this.prisma.user.findMany({
            where: {
                tests: {
                    some: {
                        answers: { not: {} }
                    }
                }
            },
            select: { telegramId: true }
        });
        const message = '🔥 نتیجه تست خیانت با تخفیف ویژه! 🔥\n\n<s>۹۹۹ هزار تومان</s>\n💥 فقط امروز: ۳۳۳ هزار تومان 💥\n\n⏰ فرصت طلایی فقط ۱ روز باقی مانده!\n✨ الان یا هیچوقت!';


        for (const user of users) {
            try {
                await this.bot.telegram.sendMessage(user.telegramId, message, {
                    parse_mode: 'HTML'
                });
            } catch (error) {
                console.log(`Failed to send to ${user.telegramId}:`, error);
            }
        }

        return { sent: 1 };
    }

    @Get('sta')
    async sendSta(@Query('message') message: string) {
        const users = await this.prisma.user.findMany({
            select: { telegramId: true }
        });
    
        for (const user of users) {
            try {
                await this.bot.telegram.sendMessage(user.telegramId, message, {
                    parse_mode: 'HTML'
                });
            } catch (error) {
                console.log(`Failed to send to ${user.telegramId}:`, error);
            }
        }
    
        return { sent: users.length };
    }


    @Get('crash-err')
    crashErr() {
        setTimeout(() => {
            throw new Error('Test crash for PM2 notification');
        }, 1000);
        return 'Crashing Err in 1 second...';
    }

    @Get('test-logs')
    logUseAllLoggers() {
        console.log('🌻 CONSOLE.lOG');
        Logger.log('🌻 Logger.log');
        return '🌻 logged';
    }




    @Get()
    async landing(@Res() res: Response) {
        const html = `
            <!DOCTYPE html>
            <html>
            <head>
                <title>همسر خائن - دکتر پیترسون</title>
                <style>
                    body { margin: 0; padding: 0; }
                    iframe { width: 100%; height: 100vh; border: none; }
                </style>
            </head>
            <body>
                <iframe src="https://radarekhianat.netlify.app/" 
                        title="Embedded Site">
                </iframe>
            </body>
            </html>
        `;
        res.setHeader('Content-Type', 'text/html');
        res.send(html);
    }






    @Get('health')
    async healthCheck() {
        const checks = {
            timestamp: new Date().toISOString(),
            status: 'healthy',
            services: {} as any,
            bot: {} as any,
            environment: {} as any
        };

        try {
            await this.prisma.$queryRaw`SELECT 1`;
            checks.services.database = { status: 'connected' };
        } catch (error: any) {
            checks.services.database = { status: 'failed', error: error.message };
            checks.status = 'unhealthy';
        }

        try {
            const me = await this.bot.telegram.getMe();
            checks.bot = {
                status: 'connected',
                username: me.username,
                id: me.id,
                webhook_info: await this.bot.telegram.getWebhookInfo()
            };
        } catch (error: any) {
            checks.bot = { status: 'failed', error: error.message };
            checks.status = 'unhealthy';
        }

        return checks;
    }




}