<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateOtpVerification extends Migration
{
    public function up(): void
    {
        // MySQL allows multiple NULLs in a unique index, so this is safe
        // for any existing rows where phone was never collected — it only
        // enforces uniqueness among rows that DO have a phone number.
        $this->db->query('ALTER TABLE users ADD UNIQUE KEY uq_users_phone (phone)');

        $this->forge->addColumn('users', [
            'mobile_verified_at' => ['type' => 'TIMESTAMP', 'null' => true, 'after' => 'email_verified_at'],
        ]);

        $this->forge->addField([
            'id'         => ['type' => 'BIGINT', 'unsigned' => true, 'auto_increment' => true],
            'user_id'    => ['type' => 'BIGINT', 'unsigned' => true],
            'channel'    => ['type' => 'ENUM', 'constraint' => ['email', 'mobile']],
            'code'       => ['type' => 'VARCHAR', 'constraint' => 10],
            'destination' => ['type' => 'VARCHAR', 'constraint' => 150], // the email or phone the code was sent to
            'attempts'   => ['type' => 'INT', 'unsigned' => true, 'default' => 0],
            'expires_at' => ['type' => 'TIMESTAMP'],
            'verified_at' => ['type' => 'TIMESTAMP', 'null' => true],
            'created_at' => ['type' => 'TIMESTAMP', 'null' => true],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->addKey(['user_id', 'channel']);
        $this->forge->addForeignKey('user_id', 'users', 'id', 'CASCADE', 'CASCADE');
        $this->forge->createTable('otp_verifications', true, ['ENGINE' => 'InnoDB']);
    }

    public function down(): void
    {
        $this->forge->dropTable('otp_verifications', true);
        $this->forge->dropColumn('users', 'mobile_verified_at');
        $this->db->query('ALTER TABLE users DROP INDEX uq_users_phone');
    }
}
