<?php

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

/**
 * Web-push subscriptions for the BMS PWAs (employee + client). BMS-native —
 * built on minishlink/web-push directly so the module stays portable (no
 * dependency on the PortalApi push layer).
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('bms_push_subscriptions')) {
            return;
        }
        Schema::create('bms_push_subscriptions', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->enum('guard', ['client', 'employee'])->default('employee');
            $t->unsignedInteger('subject_id'); // contact_id (client) or user_id (employee)
            $t->text('endpoint');
            $t->char('endpoint_hash', 64);
            $t->string('p256dh', 255)->nullable();
            $t->string('auth', 255)->nullable();
            $t->string('ua', 255)->nullable();
            $t->dateTime('last_used_at')->nullable();
            $t->timestamps();
            $t->index(['business_id', 'guard', 'subject_id']);
            $t->unique(['endpoint_hash'], 'bms_push_endpoint_unique');
        });
    }

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