<?php

/**
 * @psalm-this Mage_Core_Model_Resource_Setup
 */
$installer = $this;

$installer->startSetup();

$conn = $installer->getConnection();
$queueTable = $installer->getTable("core/email_queue");

if( ! $conn->tableColumnExists($queueTable, "completed_at")) {
    $conn->addColumn($queueTable, "completed_at", [
        "type" => Varien_Db_Ddl_Table::TYPE_TIMESTAMP,
        "comment" => "Timestamp when the email was successfully sent",
        "default" => null,
        "nullable" => true,
    ]);
}

$tableIndices = [
    "core/email_queue" => [
        ["completed_at"],
        ["processed_at", "completed_at"],
    ],
];

foreach($tableIndices as $model => $indices) {
    $table = $installer->getTable($model);
    $existingIndexes = $conn->getIndexList($table);

    foreach($indices as $fields) {
        $name = $conn->getIndexName($model, $fields);

        if( ! array_key_exists(strtoupper($name), $existingIndexes)) {
            $conn->addIndex($table, $name, $fields);
        }
    }
}

$installer->endSetup();
