<?php

declare(strict_types=1);

namespace App\Domain\SmartLink\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\ForeignKeyAction;
use App\Framework\Database\Schema\Schema;

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

        $schema->create('analytics_aggregates', function (Blueprint $table) {
            $table->id(); // AUTO_INCREMENT primary key
            $table->string('link_id', 26);
            $table->date('date');
            $table->integer('total_clicks')->default(0);
            $table->integer('unique_clicks')->default(0);
            $table->integer('conversions')->default(0);
            $table->json('country_breakdown'); // {"US": 150, "DE": 80, ...}
            $table->json('device_breakdown'); // {"mobile": 180, "desktop": 50}
            $table->json('service_breakdown'); // {"spotify": 120, "apple_music": 110}
            $table->timestamp('created_at');
            $table->timestamp('updated_at');

            $table->unique(['link_id', 'date']); // One row per link per date
            $table->foreign('link_id')->references('id')->on('smart_links')->onDelete(ForeignKeyAction::CASCADE);
            $table->index('date');
        });

        $schema->execute();
    }

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

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

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

    public function getDescription(): string
    {
        return 'CreateAnalyticsAggregatesTable';
    }
}
