<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Self-service password reset, SMS-based via Hubtel (reusing the
 * HubtelService already built in Phase 3) rather than email — this app
 * has no email-sending infrastructure, and SMS is the more reliable
 * channel for hotel staff in practice. A user with no phone on file
 * can't use self-service reset and is directed to their manager instead
 * (see ForgotPasswordController).
 *
 * `code` is a 6-digit numeric string, single-use, short-lived. Requesting
 * a new code invalidates any previous unused one for that user (see
 * PasswordResetCodeModel::generateFor()) rather than allowing several
 * valid codes to exist at once.
 */
class CreatePasswordResetCodesTable 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('password_reset_codes');
    }

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