<?php

declare(strict_types=1);

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;
use RuntimeException;

final class EnsureWhatsappGroupLinksSchoolYearIndex extends Migration
{
    public function up(): void
    {
        if ($this->db->DBDriver !== 'MySQLi') {
            throw new RuntimeException('This migration requires MySQL/MariaDB through the MySQLi driver.');
        }

        if (! $this->db->tableExists('whatsapp_group_links')
            || ! $this->db->fieldExists('school_year', 'whatsapp_group_links')) {
            return;
        }

        $indexed = $this->db->query(
            'SELECT COUNT(*) AS aggregate
             FROM information_schema.STATISTICS
             WHERE TABLE_SCHEMA = DATABASE()
               AND TABLE_NAME = ?
               AND COLUMN_NAME = ?',
            ['whatsapp_group_links', 'school_year']
        )->getRow();

        if ((int) ($indexed->aggregate ?? 0) > 0) {
            return;
        }

        $this->db->query(
            'ALTER TABLE `whatsapp_group_links` ADD INDEX `idx_sy_whatsapp_group_links_school_year` (`school_year`)'
        );
    }

    public function down(): void
    {
        if ($this->db->tableExists('whatsapp_group_links')) {
            $this->db->query('ALTER TABLE `whatsapp_group_links` DROP INDEX `idx_sy_whatsapp_group_links_school_year`');
        }
    }
}
