<?php
use Index\Data\IDbConnection;
use Index\Data\Migration\IDbMigration;

final class RedoWarningsTable_20230726_210150 implements IDbMigration {
    public function migrate(IDbConnection $conn): void {
        $conn->execute('
            CREATE TABLE msz_users_warnings (
                warn_id      INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
                user_id      INT(10) UNSIGNED NOT NULL,
                mod_id       INT(10) UNSIGNED     NULL DEFAULT NULL,
                warn_body    TEXT             NOT NULL,
                warn_created TIMESTAMP        NOT NULL DEFAULT current_timestamp(),
                PRIMARY KEY (warn_id),
                KEY users_warnings_user_foreign (user_id),
                KEY users_warnings_mod_foreign (mod_id),
                KEY users_warnings_created_index (warn_created),
                CONSTRAINT users_warnings_user_foreign
                    FOREIGN KEY (user_id)
                    REFERENCES msz_users (user_id)
                    ON UPDATE CASCADE
                    ON DELETE CASCADE,
                CONSTRAINT users_warnings_mod_foreign
                    FOREIGN KEY (mod_id)
                    REFERENCES msz_users (user_id)
                    ON UPDATE CASCADE
                    ON DELETE SET NULL
            ) ENGINE=InnoDB COLLATE=utf8mb4_bin
        ');

        // migrate existing warnings, public and private note have been merged but that's fine in prod
        // still specifying type = 1 as well even though that should be the only type remaining
        $conn->execute('
            INSERT INTO msz_users_warnings (user_id, mod_id, warn_body, warn_created)
            SELECT user_id, issuer_id, TRIM(CONCAT(COALESCE(warning_note, ""), "\n", COALESCE(warning_note_private, ""))), warning_created
            FROM msz_user_warnings
            WHERE warning_type = 1
        ');

        // drop the old table with non-plural "user"
        $conn->execute('DROP TABLE msz_user_warnings');
    }
}
