<?php

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

/**
 * Client portal auth options (3 methods like the Vet PWA): phone OTP, email
 * OTP, and a password. Adds a hashed portal password on the contact and
 * email/channel columns on the OTP table so codes can be sent by email too.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('contacts') && ! Schema::hasColumn('contacts', 'bms_portal_password')) {
            Schema::table('contacts', function (Blueprint $t) {
                $t->string('bms_portal_password')->nullable()->after('mobile');
            });
        }

        Schema::table('bms_client_otps', function (Blueprint $t) {
            if (! Schema::hasColumn('bms_client_otps', 'email')) {
                $t->string('email')->nullable()->after('phone');
            }
            if (! Schema::hasColumn('bms_client_otps', 'channel')) {
                $t->string('channel', 20)->default('phone')->after('email');
            }
        });

        // Email-only codes have no phone — relax the NOT NULL (raw, avoids dbal).
        try {
            \DB::statement('ALTER TABLE `bms_client_otps` MODIFY `phone` VARCHAR(191) NULL');
        } catch (\Throwable $e) {
            // ignore on drivers that don't support MODIFY / already nullable
        }
    }

    public function down(): void
    {
        if (Schema::hasColumn('contacts', 'bms_portal_password')) {
            Schema::table('contacts', fn (Blueprint $t) => $t->dropColumn('bms_portal_password'));
        }
        Schema::table('bms_client_otps', function (Blueprint $t) {
            foreach (['email', 'channel'] as $c) {
                if (Schema::hasColumn('bms_client_otps', $c)) {
                    $t->dropColumn($c);
                }
            }
        });
    }
};
