<?php

declare(strict_types=1);

use Bot\Infrastructure\Repository\Database\DatabaseUserRepository;
use Bot\Infrastructure\Repository\Database\DatabaseAdminRepository;
use Bot\Infrastructure\Repository\InMemoryUserRepository;
use Bot\Infrastructure\Repository\InMemoryAdminRepository;
use Bot\Infrastructure\Repository\InMemoryMediaRepository;
use Bot\Infrastructure\Repository\InMemoryAnalyticsRepository;
use Bot\Infrastructure\Repository\InMemoryPaymentRepository;
use Bot\Infrastructure\Repository\InMemoryAdsRepository;

/**
 * ایجاد PDO connection برای دیتابیس
 */
function createDatabaseConnection(): ?PDO
{
    $dbHost = $_ENV['DB_HOST'] ?? 'localhost';
    $dbPort = isset($_ENV['DB_PORT']) ? (int) $_ENV['DB_PORT'] : 3306;
    $dbName = $_ENV['DB_DATABASE'] ?? $_ENV['DB_NAME'] ?? '';
    $dbUser = $_ENV['DB_USERNAME'] ?? $_ENV['DB_USER'] ?? '';
    $dbPass = $_ENV['DB_PASSWORD'] ?? '';
    
    if (empty($dbName) || empty($dbUser)) {
        return null;
    }
    
    try {
        $dsn = "mysql:host={$dbHost};port={$dbPort};dbname={$dbName};charset=utf8mb4";
        $pdo = new PDO($dsn, $dbUser, $dbPass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
        return $pdo;
    } catch (PDOException $e) {
        return null;
    }
}

/**
 * بررسی اینکه آیا دیتابیس نصب شده است
 */
function isDatabaseInstalled(): bool
{
    // بررسی در دو مسیر ممکن (برای سازگاری)
    // مسیر 1: از public/partials/database-repositories.php به bot/.database_installed
    $databaseConfigFile1 = __DIR__ . '/../../.database_installed';
    // مسیر 2: از public/partials/database-repositories.php به bot/.database_installed (مسیر جایگزین)
    $databaseConfigFile2 = __DIR__ . '/../../../.database_installed';
    
    $exists = file_exists($databaseConfigFile1) || file_exists($databaseConfigFile2);
    
    return $exists;
}

