<?php

declare(strict_types=1);

namespace DoctrineMigrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

final class Version20251010102708 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Split signal coordinates into user and signal embeddables';
    }

    public function up(Schema $schema): void
    {
        if ($this->connection->getDatabasePlatform()->getName() !== 'sqlite') {
            return;
        }

        if (! $schema->hasTable('signals')) {
            return;
        }

        $table = $schema->getTable('signals');
        if (! $table->hasColumn('lat') || ! $table->hasColumn('lng')) {
            return;
        }

        $this->addSql('CREATE TABLE __temp__signals (id CHAR(36) NOT NULL, user_key VARCHAR(64) NOT NULL, created_at DATETIME NOT NULL, user_lat DOUBLE PRECISION NOT NULL, user_lng DOUBLE PRECISION NOT NULL, signal_lat DOUBLE PRECISION NOT NULL, signal_lng DOUBLE PRECISION NOT NULL, PRIMARY KEY(id))');
        $this->addSql('INSERT INTO __temp__signals (id, user_key, created_at, user_lat, user_lng, signal_lat, signal_lng) SELECT id, user_key, created_at, lat, lng, lat, lng FROM signals');
        $this->addSql('DROP TABLE signals');
        $this->addSql('ALTER TABLE __temp__signals RENAME TO signals');
        $this->addSql('CREATE INDEX idx_signals_created_at ON signals (created_at)');
        $this->addSql('CREATE INDEX idx_signals_user_key ON signals (user_key)');
    }

    public function down(Schema $schema): void
    {
        if ($this->connection->getDatabasePlatform()->getName() !== 'sqlite') {
            return;
        }

        if (! $schema->hasTable('signals')) {
            return;
        }

        $table = $schema->getTable('signals');
        if (! $table->hasColumn('user_lat') || ! $table->hasColumn('user_lng')) {
            return;
        }

        $this->addSql('CREATE TABLE __temp__signals (id CHAR(36) NOT NULL, user_key VARCHAR(64) NOT NULL, lat DOUBLE PRECISION NOT NULL, lng DOUBLE PRECISION NOT NULL, created_at DATETIME NOT NULL, PRIMARY KEY(id))');
        $this->addSql('INSERT INTO __temp__signals (id, user_key, lat, lng, created_at) SELECT id, user_key, signal_lat, signal_lng, created_at FROM signals');
        $this->addSql('DROP TABLE signals');
        $this->addSql('ALTER TABLE __temp__signals RENAME TO signals');
        $this->addSql('CREATE INDEX idx_signals_created_at ON signals (created_at)');
        $this->addSql('CREATE INDEX idx_signals_user_key ON signals (user_key)');
    }
}
