<?php
declare(strict_types=1);

return static function (PDO $pdo): void {
    $requiredTables = ['send_queue', 'email_opens', 'email_link_tracking', 'email_bounces', 'recipients', 'pdf_download_stats'];
    installRequireCoreTables($pdo, $requiredTables);

    $indexChecks = [
        ['send_queue', 'idx_sq_status_sent_at'],
        ['send_queue', 'idx_sq_status_created_at'],
        ['send_queue', 'idx_sq_campaign_status_sent_at'],
        ['send_queue', 'idx_sq_list_status_sent_at'],
        ['email_opens', 'idx_email_opens_opened_at_queue'],
        ['email_link_tracking', 'idx_email_link_tracking_clicked_at_queue'],
        ['email_bounces', 'idx_email_bounces_logged_at'],
        ['email_bounces', 'idx_email_bounces_queue_logged_at'],
        ['recipients', 'idx_recipients_unsubscribed_at'],
        ['pdf_download_stats', 'idx_pdf_download_stats_downloaded_at'],
    ];

    $missingIndex = false;
    foreach ($indexChecks as [$table, $index]) {
        if (!installHasIndex($pdo, $table, $index)) {
            $missingIndex = true;
            break;
        }
    }

    if (!$missingIndex) {
        return;
    }

    installRunSqlFile($pdo, installRootPath() . '/install/sql/stats_index_optimization.sql');
};