<?php

declare(strict_types=1);

namespace HackerDivergents\World\Application;

require_once __DIR__
    . '/../Domain/WorldRoundId.php';

require_once __DIR__
    . '/../Domain/WorldServerNetworkEndpointId.php';

require_once __DIR__
    . '/../Domain/VirtualNetworkRoundEndpointId.php';

use HackerDivergents\World\Domain\VirtualNetworkRoundEndpointId;
use HackerDivergents\World\Domain\WorldRoundId;
use HackerDivergents\World\Domain\WorldServerNetworkEndpointId;
use PDO;
use RuntimeException;
use Throwable;

final class WorldRoundRotationService
{
    /**
     * Encerra a rodada ativa e cria a próxima rodada.
     *
     * O método preserva:
     *
     * - identidade permanente dos world_servers;
     * - histórico em player_server_round_discoveries;
     * - endpoints históricos das rodadas anteriores.
     *
     * O método reseta:
     *
     * - player_server_discoveries;
     * - IP operacional atual de cada world_server.
     */
    public function rotate(
        PDO $pdo,
        ?string $roundName = null
    ): array {
        $ownsTransaction =
            !$pdo->inTransaction();

        if ($ownsTransaction) {
            $pdo->beginTransaction();
        }

        try {
            $currentRound =
                $this->lockActiveRound(
                    $pdo
                );

            $servers =
                $this->lockActiveServers(
                    $pdo
                );

            if ($servers === []) {
                throw new RuntimeException(
                    'world_round_rotation_no_active_servers'
                );
            }

            $nextRoundNumber =
                ((int) $currentRound['round_number'])
                + 1;

            $newRoundPublicId =
                WorldRoundId::generate()
                    ->value();

            $newRoundName =
                $this->normalizeRoundName(
                    $roundName,
                    $nextRoundNumber
                );

            $rotationTime =
                $this->loadDatabaseTimestamp(
                    $pdo
                );

            /*
            |--------------------------------------------------------------------------
            | COMPLETE CURRENT ROUND
            |--------------------------------------------------------------------------
            */

            $completeRound =
                $pdo->prepare(
                    <<<'SQL'
UPDATE world_rounds

SET
    status =
        'completed',

    ended_at =
        :ended_at,

    updated_at =
        CURRENT_TIMESTAMP(6)

WHERE public_id =
    :public_id

AND status =
    'active'
SQL
                );

            $completeRound->execute([
                'ended_at' =>
                    $rotationTime,

                'public_id' =>
                    $currentRound['public_id'],
            ]);

            if ($completeRound->rowCount() !== 1) {
                throw new RuntimeException(
                    'world_round_rotation_complete_failed'
                );
            }

            /*
            |--------------------------------------------------------------------------
            | DEACTIVATE CURRENT ROUND ENDPOINTS
            |--------------------------------------------------------------------------
            */

            $deactivateEndpoints =
                $pdo->prepare(
                    <<<'SQL'
UPDATE world_server_network_endpoints

SET
    active =
        0,

    deactivated_at =
        :deactivated_at,

    updated_at =
        CURRENT_TIMESTAMP(6)

WHERE round_public_id =
    :round_public_id

AND active =
    1

AND deactivated_at IS NULL
SQL
                );

            $deactivateEndpoints->execute([
                'deactivated_at' =>
                    $rotationTime,

                'round_public_id' =>
                    $currentRound['public_id'],
            ]);

            /*
            |--------------------------------------------------------------------------
            | CREATE NEXT ROUND
            |--------------------------------------------------------------------------
            */

            $createRound =
                $pdo->prepare(
                    <<<'SQL'
INSERT INTO world_rounds (
    public_id,
    round_number,
    name,
    status,
    started_at,
    ended_at
)
VALUES (
    :public_id,
    :round_number,
    :name,
    'active',
    :started_at,
    NULL
)
SQL
                );

            $createRound->execute([
                'public_id' =>
                    $newRoundPublicId,

                'round_number' =>
                    $nextRoundNumber,

                'name' =>
                    $newRoundName,

                'started_at' =>
                    $rotationTime,
            ]);

            /*
            |--------------------------------------------------------------------------
            | GENERATE ROUND NETWORK
            |--------------------------------------------------------------------------
            */

            /*
            |--------------------------------------------------------------------------
            | RESERVE EVERY CURRENT WORLD SERVER IP
            |--------------------------------------------------------------------------
            |
            | world_servers.virtual_ip is globally UNIQUE.
            |
            | During sequential updates, a newly generated IP must not equal
            | the old IP of ANY server because that row may not have been
            | updated yet.
            |--------------------------------------------------------------------------
            */

            $reservedServerIps = [];

            foreach ($servers as $server) {
                $reservedServerIps[
                    (string) $server['virtual_ip']
                ] =
                    true;
            }

            $usedIps = [];

            $newEndpoints = [];

            foreach ($servers as $server) {
                $this->retireRegisteredVirtualIp(
                    $pdo,
                    (string) $server['virtual_ip'],
                    $rotationTime
                );

                $endpointPublicId =
                    WorldServerNetworkEndpointId::generate()
                        ->value();

                $virtualIp =
                    $this->allocateGlobalVirtualIp(
                        $pdo,
                        $newRoundPublicId,
                        'world_server',
                        (string) $server['public_id'],
                        'world_server_endpoint',
                        $endpointPublicId,
                        $rotationTime
                    );

                $usedIps[$virtualIp] =
                    true;

                $insertEndpoint =
                    $pdo->prepare(
                        <<<'SQL'
INSERT INTO world_server_network_endpoints (
    public_id,
    round_public_id,
    server_public_id,
    virtual_ip,
    active,
    activated_at,
    deactivated_at
)
VALUES (
    :public_id,
    :round_public_id,
    :server_public_id,
    :virtual_ip,
    1,
    :activated_at,
    NULL
)
SQL
                    );

                $insertEndpoint->execute([
                    'public_id' =>
                        $endpointPublicId,

                    'round_public_id' =>
                        $newRoundPublicId,

                    'server_public_id' =>
                        $server['public_id'],

                    'virtual_ip' =>
                        $virtualIp,

                    'activated_at' =>
                        $rotationTime,
                ]);

                /*
                |--------------------------------------------------------------------------
                | LEGACY CURRENT-IP CACHE
                |--------------------------------------------------------------------------
                */

                $updateServer =
                    $pdo->prepare(
                        <<<'SQL'
UPDATE world_servers

SET
    virtual_ip =
        :virtual_ip,

    updated_at =
        CURRENT_TIMESTAMP(6)

WHERE public_id =
    :public_id
SQL
                    );

                $updateServer->execute([
                    'virtual_ip' =>
                        $virtualIp,

                    'public_id' =>
                        $server['public_id'],
                ]);

                if ($updateServer->rowCount() !== 1) {
                    throw new RuntimeException(
                        'world_round_rotation_server_ip_update_failed'
                    );
                }

                $newEndpoints[] = [
                    'public_id' =>
                        $endpointPublicId,

                    'server_public_id' =>
                        (string) $server['public_id'],

                    'previous_virtual_ip' =>
                        (string) $server['virtual_ip'],

                    'virtual_ip' =>
                        $virtualIp,
                ];
            }

            /*
            |--------------------------------------------------------------------------
            | ROTATE PLAYER / MACHINE / RELAY / SERVICE ENDPOINTS
            |--------------------------------------------------------------------------
            |
            | virtual_network_endpoints remains the operational compatibility
            | cache. virtual_network_round_endpoints stores the authoritative
            | snapshot for each round.
            |--------------------------------------------------------------------------
            */

            $virtualNetworkEndpoints =
                $this->lockActiveVirtualNetworkEndpoints(
                    $pdo
                );

            /*
            |--------------------------------------------------------------------------
            | DEACTIVATE CURRENT ROUND VIRTUAL NETWORK SNAPSHOTS
            |--------------------------------------------------------------------------
            */

            $deactivateVirtualNetworkSnapshots =
                $pdo->prepare(
                    <<<'SQL'
UPDATE virtual_network_round_endpoints

SET
    active =
        0,

    deactivated_at =
        :deactivated_at,

    updated_at =
        CURRENT_TIMESTAMP(6)

WHERE round_public_id =
    :round_public_id

AND active =
    1

AND deactivated_at IS NULL
SQL
                );

            $deactivateVirtualNetworkSnapshots->execute([
                'deactivated_at' =>
                    $rotationTime,

                'round_public_id' =>
                    $currentRound['public_id'],
            ]);

            /*
            |--------------------------------------------------------------------------
            | RESERVE EVERY CURRENT OPERATIONAL IP
            |--------------------------------------------------------------------------
            |
            | virtual_network_endpoints.virtual_ip is globally UNIQUE.
            |
            | During a sequential rotation a new IP must therefore not equal
            | the current IP of ANY endpoint, including rows that have not yet
            | been updated.
            |--------------------------------------------------------------------------
            */

            $reservedVirtualNetworkIps = [];

            foreach (
                $virtualNetworkEndpoints
                as $virtualNetworkEndpoint
            ) {
                $reservedVirtualNetworkIps[
                    (string)
                        $virtualNetworkEndpoint['virtual_ip']
                ] =
                    true;
            }

            $usedVirtualNetworkIps = [];

            $newVirtualNetworkEndpoints = [];

            foreach (
                $virtualNetworkEndpoints
                as $virtualNetworkEndpoint
            ) {
                $virtualNetworkOwner =
                    $this->resolveVirtualNetworkOwner(
                        $virtualNetworkEndpoint
                    );

                $this->retireRegisteredVirtualIp(
                    $pdo,
                    (string) $virtualNetworkEndpoint['virtual_ip'],
                    $rotationTime
                );

                $newVirtualIp =
                    $this->allocateGlobalVirtualIp(
                        $pdo,
                        $newRoundPublicId,
                        $virtualNetworkOwner['owner_type'],
                        $virtualNetworkOwner['owner_public_id'],
                        'virtual_network_endpoint',
                        (string) $virtualNetworkEndpoint['public_id'],
                        $rotationTime
                    );

                $usedVirtualNetworkIps[
                    $newVirtualIp
                ] =
                    true;

                /*
                |--------------------------------------------------------------------------
                | UPDATE OPERATIONAL COMPATIBILITY CACHE
                |--------------------------------------------------------------------------
                */

                $updateVirtualNetworkEndpoint =
                    $pdo->prepare(
                        <<<'SQL'
UPDATE virtual_network_endpoints

SET
    virtual_ip =
        :virtual_ip,

    updated_at =
        CURRENT_TIMESTAMP(6)

WHERE public_id =
    :public_id

AND active =
    1
SQL
                    );

                $updateVirtualNetworkEndpoint->execute([
                    'virtual_ip' =>
                        $newVirtualIp,

                    'public_id' =>
                        $virtualNetworkEndpoint['public_id'],
                ]);

                if (
                    $updateVirtualNetworkEndpoint->rowCount()
                    !== 1
                ) {
                    throw new RuntimeException(
                        'world_round_rotation_virtual_network_ip_update_failed'
                    );
                }

                /*
                |--------------------------------------------------------------------------
                | CREATE NEW ROUND SNAPSHOT
                |--------------------------------------------------------------------------
                */

                $roundEndpointPublicId =
                    VirtualNetworkRoundEndpointId::generate()
                        ->value();

                $insertVirtualNetworkSnapshot =
                    $pdo->prepare(
                        <<<'SQL'
INSERT INTO virtual_network_round_endpoints (
    public_id,
    round_public_id,
    source_endpoint_public_id,
    player_public_id,
    machine_public_id,
    virtual_ip,
    endpoint_type,
    active,
    activated_at,
    deactivated_at
)
VALUES (
    :public_id,
    :round_public_id,
    :source_endpoint_public_id,
    :player_public_id,
    :machine_public_id,
    :virtual_ip,
    :endpoint_type,
    1,
    :activated_at,
    NULL
)
SQL
                    );

                $insertVirtualNetworkSnapshot->execute([
                    'public_id' =>
                        $roundEndpointPublicId,

                    'round_public_id' =>
                        $newRoundPublicId,

                    'source_endpoint_public_id' =>
                        $virtualNetworkEndpoint['public_id'],

                    'player_public_id' =>
                        $virtualNetworkEndpoint['player_public_id'],

                    'machine_public_id' =>
                        $virtualNetworkEndpoint['machine_public_id'],

                    'virtual_ip' =>
                        $newVirtualIp,

                    'endpoint_type' =>
                        $virtualNetworkEndpoint['endpoint_type'],

                    'activated_at' =>
                        $rotationTime,
                ]);

                $newVirtualNetworkEndpoints[] = [
                    'public_id' =>
                        $roundEndpointPublicId,

                    'source_endpoint_public_id' =>
                        (string)
                            $virtualNetworkEndpoint['public_id'],

                    'player_public_id' =>
                        (string)
                            $virtualNetworkEndpoint['player_public_id'],

                    'machine_public_id' =>
                        $virtualNetworkEndpoint['machine_public_id'],

                    'endpoint_type' =>
                        (string)
                            $virtualNetworkEndpoint['endpoint_type'],

                    'previous_virtual_ip' =>
                        (string)
                            $virtualNetworkEndpoint['virtual_ip'],

                    'virtual_ip' =>
                        $newVirtualIp,
                ];
            }

            /*
            |--------------------------------------------------------------------------
            | VERIFY NEW ROUND VIRTUAL NETWORK SNAPSHOTS
            |--------------------------------------------------------------------------
            */

            $virtualNetworkSnapshotCountStatement =
                $pdo->prepare(
                    <<<'SQL'
SELECT COUNT(*)

FROM virtual_network_round_endpoints

WHERE round_public_id =
    :round_public_id

AND active =
    1

AND deactivated_at IS NULL
SQL
                );

            $virtualNetworkSnapshotCountStatement->execute([
                'round_public_id' =>
                    $newRoundPublicId,
            ]);

            $virtualNetworkSnapshotCount =
                (int)
                    $virtualNetworkSnapshotCountStatement
                        ->fetchColumn();

            if (
                $virtualNetworkSnapshotCount
                !==
                count($virtualNetworkEndpoints)
            ) {
                throw new RuntimeException(
                    'world_round_rotation_virtual_network_snapshot_count_failed'
                );
            }
            /*
            |--------------------------------------------------------------------------
            | RESET CURRENT DISCOVERY CACHE
            |--------------------------------------------------------------------------
            |
            | Historical rows are intentionally untouched.
            |--------------------------------------------------------------------------
            */

            $discoveryCount =
                (int)
                    $pdo->query(
                        <<<'SQL'
SELECT COUNT(*)

FROM player_server_discoveries
SQL
                    )
                    ->fetchColumn();

            $pdo->exec(
                <<<'SQL'
DELETE FROM player_server_discoveries
SQL
            );

            /*
            |--------------------------------------------------------------------------
            | VERIFY EXACTLY ONE ACTIVE ROUND
            |--------------------------------------------------------------------------
            */

            $activeRoundCount =
                (int)
                    $pdo->query(
                        <<<'SQL'
SELECT COUNT(*)

FROM world_rounds

WHERE status =
    'active'
SQL
                    )
                    ->fetchColumn();

            if ($activeRoundCount !== 1) {
                throw new RuntimeException(
                    'world_round_rotation_active_round_contract_failed'
                );
            }

            /*
            |--------------------------------------------------------------------------
            | VERIFY ENDPOINT COUNT
            |--------------------------------------------------------------------------
            */

            $endpointCountStatement =
                $pdo->prepare(
                    <<<'SQL'
SELECT COUNT(*)

FROM world_server_network_endpoints

WHERE round_public_id =
    :round_public_id

AND active =
    1

AND deactivated_at IS NULL
SQL
                );

            $endpointCountStatement->execute([
                'round_public_id' =>
                    $newRoundPublicId,
            ]);

            $endpointCount =
                (int)
                    $endpointCountStatement->fetchColumn();

            if ($endpointCount !== count($servers)) {
                throw new RuntimeException(
                    'world_round_rotation_endpoint_count_failed'
                );
            }

            $result = [
                'previous_round' => [
                    'public_id' =>
                        (string) $currentRound['public_id'],

                    'round_number' =>
                        (int) $currentRound['round_number'],

                    'name' =>
                        (string) $currentRound['name'],

                    'status' =>
                        'completed',
                ],

                'new_round' => [
                    'public_id' =>
                        $newRoundPublicId,

                    'round_number' =>
                        $nextRoundNumber,

                    'name' =>
                        $newRoundName,

                    'status' =>
                        'active',

                    'started_at' =>
                        $rotationTime,
                ],

                'server_count' =>
                    count($servers),

                'endpoint_count' =>
                    $endpointCount,

                'cleared_current_discoveries' =>
                    $discoveryCount,

                'endpoints' =>
                    $newEndpoints,

                'virtual_network_endpoint_count' =>
                    count(
                        $virtualNetworkEndpoints
                    ),

                'virtual_network_snapshot_count' =>
                    $virtualNetworkSnapshotCount,

                'virtual_network_endpoints' =>
                    $newVirtualNetworkEndpoints,
            ];

            if ($ownsTransaction) {
                $pdo->commit();
            }

            return $result;
        } catch (Throwable $exception) {
            if (
                $ownsTransaction
                && $pdo->inTransaction()
            ) {
                $pdo->rollBack();
            }

            throw $exception;
        }
    }

    private function lockActiveRound(
        PDO $pdo
    ): array {
        $query =
            $pdo->query(
                <<<'SQL'
SELECT
    public_id,
    round_number,
    name,
    status,
    started_at,
    ended_at

FROM world_rounds

WHERE status =
    'active'

ORDER BY round_number DESC

LIMIT 2

FOR UPDATE
SQL
            );

        $rows =
            $query->fetchAll(
                PDO::FETCH_ASSOC
            );

        if ($rows === []) {
            throw new RuntimeException(
                'world_round_active_not_found'
            );
        }

        if (count($rows) !== 1) {
            throw new RuntimeException(
                'world_round_multiple_active'
            );
        }

        return $rows[0];
    }

    private function lockActiveServers(
        PDO $pdo
    ): array {
        $query =
            $pdo->query(
                <<<'SQL'
SELECT
    public_id,
    code,
    hostname,
    virtual_ip

FROM world_servers

WHERE active =
    1

ORDER BY id

FOR UPDATE
SQL
            );

        return
            $query->fetchAll(
                PDO::FETCH_ASSOC
            );
    }

    private function lockActiveVirtualNetworkEndpoints(
        PDO $pdo
    ): array {
        $query =
            $pdo->query(
                <<<'SQL'
SELECT
    public_id,
    player_public_id,
    machine_public_id,
    virtual_ip,
    endpoint_type,
    active

FROM virtual_network_endpoints

WHERE active =
    1

ORDER BY id

FOR UPDATE
SQL
            );

        return
            $query->fetchAll(
                PDO::FETCH_ASSOC
            );
    }
    private function normalizeRoundName(
        ?string $roundName,
        int $roundNumber
    ): string {
        if ($roundName === null) {
            return 'Round '
                . $roundNumber;
        }

        $roundName =
            trim(
                $roundName
            );

        if ($roundName === '') {
            throw new RuntimeException(
                'world_round_name_required'
            );
        }

        if (strlen($roundName) > 150) {
            throw new RuntimeException(
                'world_round_name_too_long'
            );
        }

        return $roundName;
    }

    private function loadDatabaseTimestamp(
        PDO $pdo
    ): string {
        $value =
            $pdo->query(
                <<<'SQL'
SELECT
    DATE_FORMAT(
        CURRENT_TIMESTAMP(6),
        '%Y-%m-%d %H:%i:%s.%f'
    )
SQL
            )
            ->fetchColumn();

        if (
            !is_string($value)
            || $value === ''
        ) {
            throw new RuntimeException(
                'world_round_rotation_timestamp_failed'
            );
        }

        return $value;
    }

