<?php
declare(strict_types=1);

use Phinx\Db\Adapter\AdapterInterface;
use Phinx\Migration\AbstractMigration;

/**
 * user_two_factor_methods — one row per enrolled second-factor method per user
 * (Plan 007 §3, reusing V1's proven column set as proper Phinx, with a real FK
 * + indexes). The secret is stored encrypted (`secret` + base64 `secret_iv`,
 * AES-256-CBC via apexl/hashing). `is_active` flips true only after a
 * verify-to-confirm. `failed_attempts` / `locked_until` drive brute-force
 * lockout. `type` is the method name (v3.0: 'totp').
 */
final class CreateUserTwoFactorMethods extends AbstractMigration
{
    public function change(): void
    {
        $this->table('user_two_factor_methods')
            ->addColumn('user_id', AdapterInterface::PHINX_TYPE_INTEGER, [
                'signed' => false,
                'null' => false,
            ])
            ->addColumn('type', AdapterInterface::PHINX_TYPE_STRING, ['limit' => 32, 'null' => false])
            ->addColumn('secret', AdapterInterface::PHINX_TYPE_TEXT, ['null' => true])
            ->addColumn('secret_iv', AdapterInterface::PHINX_TYPE_STRING, ['limit' => 64, 'null' => true])
            ->addColumn('is_active', AdapterInterface::PHINX_TYPE_BOOLEAN, ['null' => false, 'default' => false])
            ->addColumn('failed_attempts', AdapterInterface::PHINX_TYPE_INTEGER, [
                'signed' => false,
                'null' => false,
                'default' => 0,
            ])
            // Unix-timestamp columns, matching the framework's INTEGER
            // created/modified convention (users table) and DATETIME_STAMP casts.
            ->addColumn('locked_until', AdapterInterface::PHINX_TYPE_INTEGER, ['null' => true, 'default' => null])
            ->addColumn('label', AdapterInterface::PHINX_TYPE_STRING, ['limit' => 191, 'null' => true, 'default' => null])
            ->addColumn('last_used_at', AdapterInterface::PHINX_TYPE_INTEGER, ['null' => true, 'default' => null])
            ->addColumn('created', AdapterInterface::PHINX_TYPE_INTEGER, ['null' => true, 'default' => null])
            ->addColumn('created_by', AdapterInterface::PHINX_TYPE_INTEGER, ['null' => true, 'default' => null])
            ->addColumn('modified', AdapterInterface::PHINX_TYPE_INTEGER, ['null' => true, 'default' => null])
            ->addColumn('modified_by', AdapterInterface::PHINX_TYPE_INTEGER, ['null' => true, 'default' => null])
            ->addIndex(['user_id'])
            ->addIndex(['user_id', 'type'])
            ->addForeignKey('user_id', 'users', 'id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
            ->create();
    }
}
