<?php

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

/**
 * Bearer tokens for the staff/doctor PWA. Mirrors portal_owner_tokens but
 * keys to the ERP `users` table — staff authenticate as their existing user,
 * not a parallel account.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('vet_staff_tokens')) return;

        Schema::create('vet_staff_tokens', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('user_id');
            $t->unsignedInteger('business_id')->nullable();
            // sha256 of the bearer token handed to the PWA — never store plaintext.
            $t->string('token_hash', 64)->unique();
            $t->string('user_agent')->nullable();
            $t->string('ip', 45)->nullable();
            $t->timestamp('last_used_at')->nullable();
            $t->timestamp('expires_at')->nullable()->index();
            $t->timestamps();

            $t->index('user_id');
        });
    }

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