import type { NextApiRequest, NextApiResponse } from 'next';
import { Client as PgClient } from 'pg';
import mysql from 'mysql2/promise';
import { MongoClient } from 'mongodb';

/**
 * Handles testing the connection to a database.
 * This version uses native Node.js drivers for reliability and security.
 */
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    if (req.method !== 'POST') {
        return res.status(405).json({ message: 'Method Not Allowed' });
    }

    const { 
        dbType, 
        dbHost, 
        dbPort, 
        dbUser, 
        dbPassword, 
        dbName, 
        dbRequireSsl 
    } = req.body;

    if (!dbType || !dbHost || !dbPort || !dbUser) {
        return res.status(400).json({ error: 'Missing required database credentials for testing.' });
    }

    switch (dbType) {
        case 'postgresql':
            const pgClient = new PgClient({
                host: dbHost,
                port: Number(dbPort),
                user: dbUser,
                password: dbPassword,
                database: dbName,
                ssl: dbRequireSsl ? { rejectUnauthorized: false } : false,
                // ✅ **التعديل: زيادة مهلة الاتصال إلى 30 ثانية**
                connectionTimeoutMillis: 30000, 
            });

            try {
                await pgClient.connect();
                await pgClient.end();
                return res.status(200).json({ message: 'PostgreSQL connection successful!' });
            } catch (error: any) {
                return res.status(500).json({ error: error.message });
            }

        case 'mysql':
            let mysqlConnection;
            try {
                mysqlConnection = await mysql.createConnection({
                    host: dbHost,
                    port: Number(dbPort),
                    user: dbUser,
                    password: dbPassword,
                    database: dbName,
                    ssl: dbRequireSsl ? { rejectUnauthorized: false } : undefined,
                    connectTimeout: 30000, // 30 second timeout
                });
                await mysqlConnection.end();
                return res.status(200).json({ message: 'MySQL connection successful!' });
            } catch (error: any) {
                // Ensure connection is closed even if it fails
                if (mysqlConnection) await mysqlConnection.end();
                return res.status(500).json({ error: error.message });
            }

        case 'mongodb':
            const mongoURI = `mongodb://${dbUser}:${encodeURIComponent(dbPassword || '')}@${dbHost}:${dbPort}/${dbName || ''}?authSource=admin`;
            const mongoClient = new MongoClient(mongoURI, {
                ssl: dbRequireSsl,
                serverSelectionTimeoutMS: 30000, // 30 second timeout
            });
            try {
                await mongoClient.connect();
                await mongoClient.db("admin").command({ ping: 1 });
                await mongoClient.close();
                return res.status(200).json({ message: 'MongoDB connection successful!' });
            } catch (error: any) {
                await mongoClient.close();
                return res.status(500).json({ error: error.message });
            }

        default:
            return res.status(400).json({ error: 'Unsupported database type' });
    }
}

