<?php

declare(strict_types=1);

namespace App\Framework\Notification\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;
use App\Framework\Database\ValueObjects\SqlQuery;

/**
 * Create notifications table for in-app notifications
 */
final readonly class CreateNotificationsTable implements Migration
{
    public function up(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);

        $schema->createIfNotExists('notifications', function (Blueprint $table) {
            $table->string('id', 26)->primary();
            $table->string('recipient_id', 100);
            $table->string('type', 50);
            $table->string('title', 255);
            $table->text('body');
            $table->json('data')->nullable();
            $table->json('channels');
            $table->string('priority', 20)->default('normal');
            $table->string('status', 20)->default('pending');
            $table->timestamp('created_at');
            $table->timestamp('sent_at')->nullable();
            $table->timestamp('read_at')->nullable();
            $table->string('action_url')->nullable();
            $table->string('action_label', 100)->nullable();

            // Indexes
            $table->index(['recipient_id']);
            $table->index(['type']);
            $table->index(['status']);
            $table->index(['created_at']);
            $table->index(['read_at']);
        });

        $schema->execute();

        // Composite indexes for common queries
        $connection->execute(SqlQuery::create('CREATE INDEX idx_notifications_recipient_status_created ON notifications(recipient_id, status, created_at)'));
        $connection->execute(SqlQuery::create('CREATE INDEX idx_notifications_recipient_type ON notifications(recipient_id, type)'));
    }

    public function down(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);
        $schema->dropIfExists('notifications');
        $schema->execute();
    }

    public function getVersion(): MigrationVersion
    {
        return MigrationVersion::fromTimestamp("2025_10_02_000001");
    }

    public function getDescription(): string
    {
        return 'Create notifications table for in-app notification system';
    }
}
