<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateLoginSecurityTables extends Migration
{
    public function up()
    {
        // الأجهزة الموثوقة - جهاز اتأكد قبل كده بالبريد، فما يطلبش كود تاني منه
        $this->forge->addField([
            'id' => ['type' => 'BIGINT', 'unsigned' => true, 'auto_increment' => true],
            'user_id' => ['type' => 'BIGINT', 'unsigned' => true],
            'token' => ['type' => 'VARCHAR', 'constraint' => 100],
            'device_label' => ['type' => 'VARCHAR', 'constraint' => 255, 'null' => true],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
            'last_used_at' => ['type' => 'DATETIME', 'null' => true],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->addUniqueKey('token');
        $this->forge->addKey('user_id');
        $this->forge->addForeignKey('user_id', 'users', 'id', 'CASCADE', 'CASCADE');
        $this->forge->createTable('trusted_devices');

        // أكواد تأكيد الدخول المؤقتة (OTP) المرسلة بالبريد
        $this->forge->addField([
            'id' => ['type' => 'BIGINT', 'unsigned' => true, 'auto_increment' => true],
            'user_id' => ['type' => 'BIGINT', 'unsigned' => true],
            'code' => ['type' => 'VARCHAR', 'constraint' => 6],
            'is_used' => ['type' => 'TINYINT', 'constraint' => 1, 'default' => 0],
            'expires_at' => ['type' => 'DATETIME'],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->addKey('user_id');
        $this->forge->addForeignKey('user_id', 'users', 'id', 'CASCADE', 'CASCADE');
        $this->forge->createTable('login_otps');
    }

    public function down()
    {
        $this->forge->dropTable('login_otps');
        $this->forge->dropTable('trusted_devices');
    }
}
