<?php

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;

/**
 * Fix a pre-existing bug: portal_otp_challenges.expires_at was created as a MySQL
 * TIMESTAMP with "ON UPDATE CURRENT_TIMESTAMP" (MySQL's implicit behaviour for the
 * first timestamp column). Any UPDATE to a challenge row — e.g. incrementing
 * `attempts` on a wrong code — therefore silently reset expires_at to NOW(), so the
 * very next (correct) attempt was rejected as "expired". This broke OTP login after
 * a single mistype, and the public-booking OTP gate.
 *
 * Make expires_at a plain nullable timestamp that only changes when set explicitly
 * (open() always sets it). MySQL-only; harmless no-op elsewhere.
 */
class FixPortalOtpExpiresAtAutoupdate extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('portal_otp_challenges')) {
            return;
        }
        if (DB::getDriverName() === 'mysql') {
            DB::statement('ALTER TABLE portal_otp_challenges MODIFY expires_at TIMESTAMP NULL DEFAULT NULL');
        }
    }

    public function down()
    {
        if (!Schema::hasTable('portal_otp_challenges')) {
            return;
        }
        if (DB::getDriverName() === 'mysql') {
            DB::statement('ALTER TABLE portal_otp_challenges MODIFY expires_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP');
        }
    }
}
