<?php

declare(strict_types=1);

namespace App\Framework\WebPush\Migrations;

use App\Framework\Database\ConnectionInterface;
use App\Framework\Database\Migration\Migration;
use App\Framework\Database\Migration\MigrationVersion;
use App\Framework\Database\Schema\Blueprint;
use App\Framework\Database\Schema\Schema;

final readonly class CreatePushSubscriptionsTable implements Migration
{
    public function up(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);

        $schema->create('push_subscriptions', function (Blueprint $table) {
            $table->id();
            $table->string('hash', 64)->unique(); // SHA-256 hash of endpoint
            $table->text('endpoint');              // Push service endpoint URL
            $table->string('p256dh_key');         // Client public key (Base64 URL-safe)
            $table->string('auth_token');         // Client auth secret (Base64 URL-safe)
            $table->string('user_id', 255)->nullable(); // Optional user association
            $table->string('user_agent', 500)->nullable();
            $table->timestamp('created_at');
            $table->timestamp('expires_at')->nullable();
            $table->timestamp('last_used_at')->nullable();

            // Indexes
            $table->index('hash');
            $table->index('user_id');
            $table->index('expires_at');
            $table->index(['user_id', 'created_at']);
        });

        $schema->execute();
    }

    public function down(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);

        $schema->dropIfExists('push_subscriptions');
        $schema->execute();
    }

    public function getVersion(): MigrationVersion
    {
        return MigrationVersion::fromTimestamp('2025_01_10_000001');
    }

    public function getDescription(): string
    {
        return 'Create push_subscriptions table for Web Push Notifications';
    }
}
