package com.example.boidelov3;

import android.os.Handler;
import android.os.Looper;

import com.example.boidelov3.BuildConfig;
import com.impossibl.postgres.api.jdbc.PGConnection;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Gère la connexion à la base de données PostgreSQL de manière asynchrone.
 * Remplace l'obsolète AsyncTask par ExecutorService + Handler.
 *
 * SECURITY WARNING: This class is currently disabled because database credentials
 * should NEVER be stored in BuildConfig or in the app code.
 *
 * Recommended secure alternatives:
 * 1. Use a backend API that handles database connections
 * 2. Use Android Keystore for storing encrypted credentials locally
 * 3. Use Firebase Authentication or similar secure services
 *
 * To re-enable database functionality, implement one of the secure solutions above.
 */
public class DatabaseConnection {

    // Database credentials are now disabled for security
    private static final String DB_URL = "";
    private static final String USER = "";
    private static final String PASSWORD = "";

    private final ExecutorService executorService;
    private final Handler mainHandler;

    public DatabaseConnection() {
        this.executorService = Executors.newSingleThreadExecutor();
        this.mainHandler = new Handler(Looper.getMainLooper());
    }

    /**
     * Interface de callback pour le résultat de la connexion.
     */
    public interface ConnectionCallback {
        void onSuccess(PGConnection connection);
        void onFailure(Exception error);
    }

    /**
     * Connexion asynchrone à la base de données.
     *
     * @param callback Callback appelé sur le thread principal
     */
    public void connectAsync(ConnectionCallback callback) {
        executorService.execute(() -> {
            PGConnection connection = null;
            Exception error = null;

            try {
                connection = (PGConnection) DriverManager.getConnection(DB_URL, USER, PASSWORD);
            } catch (SQLException e) {
                error = e;
            }

            // Retour sur le thread principal pour notifier le résultat
            final PGConnection finalConnection = connection;
            final Exception finalError = error;

            mainHandler.post(() -> {
                if (finalError == null && finalConnection != null) {
                    callback.onSuccess(finalConnection);
                } else {
                    callback.onFailure(finalError != null ? finalError : new SQLException("Connection failed"));
                }
            });
        });
    }

    /**
     * Ferme l'executorService pour libérer les ressources.
     * À appeler dans onDestroy() de l'Activity.
     */
    public void shutdown() {
        executorService.shutdown();
    }
}
