use strict;
use warnings FATAL => 'all';
use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More;

# Initialize publisher node
my $node_publisher = PostgreSQL::Test::Cluster->new('publisher');
$node_publisher->init(allows_streaming => 'logical');
$node_publisher->append_conf('postgresql.conf', qq{
wal_level = logical
wal_sender_timeout = 0
wal_receiver_timeout = 0
shared_buffers = 40GB
max_worker_processes = 32
max_parallel_maintenance_workers = 24
max_parallel_workers = 32
synchronous_commit = off
checkpoint_timeout = 1d
max_wal_size = 24GB
min_wal_size = 15GB
autovacuum = off
max_logical_replication_workers = 15
max_sync_workers_per_subscription = 2
log_line_prefix = '%n [%p] '
max_wal_senders = 200
max_replication_slots = 200
});
$node_publisher->start;

my $count =  300000;
# Create some preexisting content on publisher
for my $i(1...10)
{
        $node_publisher->safe_psql('postgres',"CREATE TABLE t$i(a int)");
}
for my $i(1...10)
{
        $node_publisher->safe_psql('postgres', "INSERT INTO t$i VALUES(generate_series(1,$count))");
}

# Create subscriber node
my $node_subscriber = PostgreSQL::Test::Cluster->new('subscriber');
$node_subscriber->init;
$node_subscriber->append_conf('postgresql.conf', qq{
wal_level = logical
wal_sender_timeout = 0
wal_receiver_timeout = 0
shared_buffers = 40GB
max_worker_processes = 32
max_parallel_maintenance_workers = 24
max_parallel_workers = 32
synchronous_commit = off
checkpoint_timeout = 1d
max_wal_size = 24GB
min_wal_size = 15GB
autovacuum = off
max_logical_replication_workers = 15
max_sync_workers_per_subscription = 2
log_line_prefix = '%n [%p] '
max_wal_senders = 200
max_replication_slots = 200
});
$node_subscriber->start;

for my $i(1...10)
{
        $node_subscriber->safe_psql('postgres',"CREATE TABLE t$i(a int)");
}
my $publisher_connstr = $node_publisher->connstr . ' dbname=postgres';
$node_publisher->safe_psql('postgres',"CREATE PUBLICATION PUB1 FOR ALL TABLES");

use Time::HiRes qw(time);
my $start = time();
$node_subscriber->safe_psql('postgres', "CREATE SUBSCRIPTION test2 CONNECTION '$publisher_connstr' PUBLICATION pub1");
$node_subscriber->wait_for_subscription_sync($node_publisher, 'test2');

# Actual test end
my $elapsed = time() - $start;
printf("Execution time - %0.5f seconds\n", $elapsed);

my $result;
for my $i(1...10)
{
$result = $node_subscriber->safe_psql('postgres', "SELECT COUNT(*) FROM t$i");
is ($result, $count, "t$i has expected rows");
}

$node_subscriber->stop;
$node_publisher->stop;

done_testing();
