import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';

async function testConnection(name: string, url: string) {
    try {
        const prisma = new PrismaClient({
            datasources: {
                db: {
                    url: url
                }
            }
        });
        
        const start = Date.now();
        const users = await prisma.user.findMany({ take: 1 });
        const duration = Date.now() - start;
        
        await prisma.$disconnect();
        return {
            name,
            success: true,
            duration: `${duration}ms`,
            usersCount: users.length,
            message: 'Successfully connected and queried.'
        };
    } catch (e: any) {
        return {
            name,
            success: false,
            message: e.message
        };
    }
}

export async function GET() {
    const candidates = [
        {
            name: "1. TCP Localhost (localhost:3306)",
            url: "mysql://hmfupimy_dbuser:w6V%25ri%23r%5EmD%3F!)nc@localhost:3306/hmfupimy_hmf?connection_limit=1"
        },
        {
            name: "2. TCP Loopback (127.0.0.1:3306)",
            url: "mysql://hmfupimy_dbuser:w6V%25ri%23r%5EmD%3F!)nc@127.0.0.1:3306/hmfupimy_hmf?connection_limit=1"
        },
        {
            name: "3. TCP Domain Name (hmfupi.or.id:3306)",
            url: "mysql://hmfupimy_dbuser:w6V%25ri%23r%5EmD%3F!)nc@hmfupi.or.id:3306/hmfupimy_hmf?connection_limit=1"
        },
        {
            name: "4. Unix Socket /var/lib/mysql/mysql.sock",
            url: "mysql://hmfupimy_dbuser:w6V%25ri%23r%5EmD%3F!)nc@localhost/hmfupimy_hmf?socket=/var/lib/mysql/mysql.sock&connection_limit=1"
        },
        {
            name: "5. Unix Socket /tmp/mysql.sock",
            url: "mysql://hmfupimy_dbuser:w6V%25ri%23r%5EmD%3F!)nc@localhost/hmfupimy_hmf?socket=/tmp/mysql.sock&connection_limit=1"
        },
        {
            name: "6. Unix Socket /var/run/mysqld/mysqld.sock",
            url: "mysql://hmfupimy_dbuser:w6V%25ri%23r%5EmD%3F!)nc@localhost/hmfupimy_hmf?socket=/var/run/mysqld/mysqld.sock&connection_limit=1"
        }
    ];

    const results = [];
    for (const c of candidates) {
        const res = await testConnection(c.name, c.url);
        results.push(res);
    }

    return NextResponse.json({
        timestamp: new Date().toISOString(),
        message: "Database connection test results",
        results
    });
}
