<?php

declare(strict_types=1);

namespace DoctrineMigrations;

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

final class Version20240919000000 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Create signals table';
    }

    public function up(Schema $schema): void
    {
        $platform = $this->connection->getDatabasePlatform()->getName();

        if ($platform === 'postgresql') {
            $this->addSql('CREATE EXTENSION IF NOT EXISTS postgis');
            $this->addSql('CREATE TABLE signals (id UUID NOT NULL, user_key VARCHAR(64) 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, created_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, PRIMARY KEY(id))');
            $this->addSql('CREATE INDEX idx_signals_created_at ON signals (created_at)');
            $this->addSql('CREATE INDEX idx_signals_user_key ON signals (user_key)');
            $this->addSql('CREATE INDEX idx_signals_signal_location_gix ON signals USING GIST (ST_SetSRID(ST_MakePoint(signal_lng, signal_lat), 4326))');

            return;
        }

        if ($platform === 'sqlite') {
            $this->addSql('CREATE TABLE signals (id CHAR(36) NOT NULL, user_key VARCHAR(64) 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, created_at DATETIME NOT NULL, PRIMARY KEY(id))');
            $this->addSql('CREATE INDEX idx_signals_created_at ON signals (created_at)');
            $this->addSql('CREATE INDEX idx_signals_user_key ON signals (user_key)');

            return;
        }

        $this->abortIf(true, 'Migration can only be executed on postgresql or sqlite.');
    }

    public function down(Schema $schema): void
    {
        $platform = $this->connection->getDatabasePlatform()->getName();

        if ($platform === 'postgresql') {
            $this->addSql('DROP TABLE signals');
            $this->addSql('DROP EXTENSION IF EXISTS postgis');

            return;
        }

        if ($platform === 'sqlite') {
            $this->addSql('DROP TABLE signals');

            return;
        }

        $this->abortIf(true, 'Migration can only be executed on postgresql or sqlite.');
    }
}
