# Copyright (c) 2021-2025, PostgreSQL Global Development Group

use strict;
use warnings FATAL => 'all';

use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More;

# Initialize primary node
my $node_primary = PostgreSQL::Test::Cluster->new('primary');
$node_primary->init(allows_streaming => 1);
$node_primary->start;
my $backup_name = 'my_backup';

# Take backup
$node_primary->backup($backup_name);

# Create streaming standby linking to primary
my $node_standby = PostgreSQL::Test::Cluster->new('standby');
$node_standby->init_from_backup($node_primary, $backup_name,
	has_streaming => 1);
$node_standby->start;

# populate some data on primary
$node_primary->safe_psql('postgres', qq(
    CREATE TABLE t1(id INT);
    INSERT INTO t1(id) SELECT generate_series(1, 1000)
));

# get current lsn
my $current_lsn = $node_primary->safe_psql('postgres', "SELECT pg_current_wal_lsn();");
chomp($current_lsn);

# configure recovery parameter
$node_standby->append_conf('postgresql.conf', "recovery_target_lsn = '$current_lsn'");
$node_standby->append_conf('postgresql.conf', 'recovery_target_inclusive = false');
$node_standby->append_conf('postgresql.conf', 'recovery_target_action = promote');

# restart the node
$node_standby->restart;

# check for recovery
ok( $node_standby->poll_query_until(
		'postgres', 'SELECT NOT pg_is_in_recovery()'),
	'promoted standby is not in recovery');


done_testing();
