<?php

namespace PortalPeople\NgaugeBackupSql\migrations;

use yii\db\Migration;

/**
 * Creates table for backup history tracking
 */
class m260210_000000_create_backup_history_table extends Migration
{
    /**
     * @inheritdoc
     */
    public function safeUp()
    {
        // Skip if table already exists
        if ($this->db->getTableSchema('{{%backup_history}}') !== null) {
            echo "Table 'backup_history' already exists. Skipping creation.\n";
            return;
        }

        $this->createTable('{{%backup_history}}', [
            'id' => $this->primaryKey(),
            'table_name' => $this->string(255)->notNull()->comment('Database table name'),
            'filename' => $this->string(255)->notNull()->comment('Backup filename'),
            'file_size' => $this->bigInteger()->defaultValue(0)->comment('File size in bytes'),
            'status' => $this->string(50)->notNull()->comment('Operation status: success, failed, restored, restore_failed'),
            'error_message' => $this->text()->null()->comment('Error message if operation failed'),
            'created_at' => $this->integer()->notNull()->comment('Timestamp when operation occurred'),
            'created_by' => $this->integer()->null()->comment('User ID who performed the operation'),
        ], 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB');

        // Create indexes
        $this->createIndex(
            'idx-backup_history-table_name',
            '{{%backup_history}}',
            'table_name'
        );

        $this->createIndex(
            'idx-backup_history-status',
            '{{%backup_history}}',
            'status'
        );

        $this->createIndex(
            'idx-backup_history-created_at',
            '{{%backup_history}}',
            'created_at'
        );

        $this->createIndex(
            'idx-backup_history-filename',
            '{{%backup_history}}',
            'filename'
        );
    }

    /**
     * @inheritdoc
     */
    public function safeDown()
    {
        $this->dropTable('{{%backup_history}}');
    }
}
