<?php

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

/**
 * Stores FCM / APNs device tokens for push notification delivery.
 *
 * Why per-user (not per-workspace): a single user may belong to several
 * workspaces and switch between them in the app, but their device should
 * receive notifications for whichever workspace is currently active. The
 * `workspace_id` column captures the active workspace at registration
 * time and is updated on each /devices upsert.
 *
 * Uniqueness is on `token` alone — FCM/APNs guarantee tokens are unique
 * per app install, so the same token must point to a single user. If a
 * user signs out and another user signs in on the same phone, the token
 * gets re-bound (the controller updates user_id on conflict).
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('device_tokens')) {
            return;
        }

        Schema::create('device_tokens', function (Blueprint $t) {
            $t->id();
            $t->foreignId('user_id')->constrained()->cascadeOnDelete();
            $t->foreignId('workspace_id')->nullable()->constrained()->nullOnDelete();
            // FCM tokens are up to ~163 chars, APNs up to 200 hex chars.
            // Keep room for future provider changes.
            $t->string('token', 512);
            $t->enum('platform', ['android', 'ios', 'web'])->default('android');
            $t->string('app_version', 32)->nullable();
            $t->string('device_name', 128)->nullable();
            $t->string('locale', 8)->nullable();
            $t->timestamp('last_seen_at')->nullable();
            $t->timestamps();

            $t->unique('token');
            $t->index(['user_id', 'workspace_id']);
        });
    }

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