<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Two-factor login — every staff login now requires a second SMS code
 * after the password check succeeds, not just password reset. Same
 * shape/lifecycle as password_reset_codes (single-use, short-lived,
 * requesting a new code invalidates any previous unused one), kept as
 * its own table rather than reused — a code meant to let someone INTO
 * an account and a code meant to let someone CHANGE its password are
 * different enough security boundaries to keep structurally separate,
 * even though the columns look identical. See AuthController and
 * LoginOtpCodeModel.
 */
class CreateLoginOtpCodesTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'user_id' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
            ],
            'code' => [
                'type'       => 'VARCHAR',
                'constraint' => 6,
            ],
            'expires_at' => [
                'type' => 'DATETIME',
            ],
            'used_at' => [
                'type' => 'DATETIME',
                'null' => true,
            ],
            'created_at' => [
                'type' => 'DATETIME',
            ],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addKey('user_id');
        $this->forge->addForeignKey('user_id', 'users', 'id', '', 'CASCADE');
        $this->forge->createTable('login_otp_codes');
    }

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