<?php

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

/**
 * Phase 3 — authenticated vehicle-owner portal accounts (phone-OTP or password),
 * with bearer tokens for the PWA/session. Mirrors the PortalApi/VetPortal owner
 * pattern but scoped to VRC and the vehicle owner's ERP contact.
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('vrc_portal_owners')) {
            Schema::create('vrc_portal_owners', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedInteger('erp_customer_id')->nullable();
                $t->string('name', 191);
                $t->string('phone', 30);
                $t->string('email', 120)->nullable();
                $t->string('password', 255)->nullable();
                $t->string('otp_code', 10)->nullable();
                $t->dateTime('otp_expires_at')->nullable();
                $t->boolean('is_active')->default(true);
                $t->dateTime('last_login_at')->nullable();
                $t->timestamps();
                $t->unique(['business_id', 'phone'], 'vrc_portal_owner_biz_phone_uniq');
                $t->index(['business_id', 'erp_customer_id'], 'vrc_portal_owner_biz_cust_idx');
            });
        }

        if (! Schema::hasTable('vrc_portal_owner_tokens')) {
            Schema::create('vrc_portal_owner_tokens', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedBigInteger('owner_id');
                $t->string('token', 80);
                $t->string('device', 120)->nullable();
                $t->dateTime('expires_at')->nullable();
                $t->timestamp('created_at')->nullable();
                $t->index(['business_id', 'owner_id'], 'vrc_portal_token_biz_owner_idx');
                $t->index('token', 'vrc_portal_token_idx');
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('vrc_portal_owner_tokens');
        Schema::dropIfExists('vrc_portal_owners');
    }
};
