<?php

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

/**
 * Web-Push subscriptions for staff devices. Mirrors portal_push_subscriptions
 * but keyed to the ERP user. Reuses the same VAPID keys (config portal_push).
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('clinic_staff_push_subscriptions')) return;

        Schema::create('clinic_staff_push_subscriptions', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('user_id');
            $t->unsignedInteger('business_id')->nullable();
            $t->string('endpoint', 500);
            $t->string('p256dh_key', 191);
            $t->string('auth_key', 64);
            $t->string('user_agent')->nullable();
            $t->json('categories')->nullable();
            $t->timestamp('last_used_at')->nullable();
            $t->timestamp('last_failed_at')->nullable();
            $t->unsignedSmallInteger('consecutive_failures')->default(0);
            $t->timestamps();

            $t->index(['business_id', 'user_id']);
        });
    }

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