<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * A record of every automated backup attempt (see RunBackup command /
 * `php spark backup:run`, and the "Run Backup Now" button on the Data
 * Backup page that fires the same path on demand). Unattended cron jobs
 * are worthless without visibility — this is what lets a manager
 * actually see "did last night's backup happen, and did the email
 * send" instead of just hoping silently. Separate from BackupController's
 * existing manual export/restore actions, which are logged to
 * activity_log like every other staff action — this table exists
 * because a *scheduled* run has no staff member to attribute it to and
 * needs its own success/failure/file-size/email-outcome record.
 */
class CreateBackupRunsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'status' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'comment'    => 'success, failed',
            ],
            'local_path' => [
                'type'       => 'VARCHAR',
                'constraint' => 255,
                'null'       => true,
            ],
            'file_size_bytes' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
                'null'       => true,
            ],
            'emailed' => [
                'type'       => 'TINYINT',
                'constraint' => 1,
                'default'    => 0,
            ],
            'email_error' => [
                'type' => 'TEXT',
                'null' => true,
            ],
            'error_message' => [
                'type' => 'TEXT',
                'null' => true,
            ],
            'triggered_by' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
                'null'       => true,
                'comment'    => 'null = scheduled cron run, a real user id = manual "Run Backup Now"',
            ],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addForeignKey('triggered_by', 'users', 'id', '', 'SET NULL');
        $this->forge->createTable('backup_runs');
    }

    public function down()
    {
        $this->forge->dropTable('backup_runs', true);
    }
}
