<?php
declare(strict_types=1);

return static function (PDO $pdo): void {
    installRequireCoreTables($pdo, ['email_link_tracking', 'recipient_tags', 'tags', 'recipient_lists', 'lists']);

    $requiredTables = ['email_link_actions', 'automation_rules', 'automation_rule_logs'];
    $missingTable = false;
    foreach ($requiredTables as $table) {
        if (!installHasTable($pdo, $table)) {
            $missingTable = true;
            break;
        }
    }

    if ($missingTable) {
        installRunSqlFile($pdo, installRootPath() . '/install/sql/add_link_automation_support.sql');
        return;
    }

    $indexChecks = [
        ['email_link_actions', 'idx_email_link_actions_tracking'],
        ['email_link_actions', 'idx_email_link_actions_tag'],
        ['automation_rules', 'idx_automation_rules_event'],
        ['automation_rule_logs', 'idx_automation_rule_logs_rule_recipient'],
    ];

    foreach ($indexChecks as [$table, $index]) {
        if (!installHasIndex($pdo, $table, $index)) {
            installRunSqlFile($pdo, installRootPath() . '/install/sql/add_link_automation_support.sql');
            return;
        }
    }

    if (!installHasColumn($pdo, 'email_link_actions', 'executed_at')) {
        $pdo->exec('ALTER TABLE email_link_actions ADD COLUMN executed_at DATETIME DEFAULT NULL AFTER only_once');
    }
};