<?php

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

/**
 * One row per owner+device that has loaded the PWA. Lets the clinic see
 *   • who installed the app to home screen (installed_at != null)
 *   • who's currently a returning visitor (last_seen_at)
 *   • per-device platform breakdown (UA-derived label)
 *
 * Push-subscription state lives in portal_push_subscriptions and is
 * joined alongside this in the analytics view.
 */
return new class extends Migration {
    public function up(): void
    {
        Schema::create('portal_owner_devices', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedBigInteger('owner_id');
            $t->foreign('owner_id')->references('id')->on('portal_owners')->onDelete('cascade');

            // sha256 of "<owner_id>:<user_agent>" — stable, anonymous per browser
            $t->string('device_hash', 64);
            $t->string('platform', 32)->nullable();      // 'ios', 'android', 'desktop', 'other'
            $t->string('user_agent')->nullable();

            $t->timestamp('first_seen_at')->nullable();
            $t->timestamp('last_seen_at')->nullable();
            $t->timestamp('installed_at')->nullable();   // first time we saw display-mode standalone

            $t->timestamps();
            $t->unique(['owner_id', 'device_hash']);
            $t->index('installed_at');
        });
    }

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