<?php
declare(strict_types=1);

require_once __DIR__ . '/../backup_lib.php';

$tz = new DateTimeZone(date_default_timezone_get());
$failures = [];

$expectTime = static function (string $label, ?DateTimeImmutable $actual, string $expected) use (&$failures): void {
    $value = $actual?->format('Y-m-d H:i');
    if ($value !== $expected) $failures[] = "{$label}: expected {$expected}, got " . ($value ?? 'null');
};
$expectBool = static function (string $label, bool $actual, bool $expected) use (&$failures): void {
    if ($actual !== $expected) $failures[] = "{$label}: expected " . ($expected ? 'true' : 'false') . ', got ' . ($actual ? 'true' : 'false');
};

$base = ['enabled' => 1, 'run_time' => '02:00', 'last_run_at' => null];
$settings = static fn(array $overrides): array => array_replace($base, $overrides);
$expectTime('daily before time', ua_backup_next_run($settings(['frequency' => 'daily']), new DateTimeImmutable('2026-08-01 01:00', $tz)), '2026-08-01 02:00');
$expectTime('daily after time', ua_backup_next_run($settings(['frequency' => 'daily']), new DateTimeImmutable('2026-08-01 03:00', $tz)), '2026-08-02 02:00');
$expectTime('weekly next monday', ua_backup_next_run($settings(['frequency' => 'weekly', 'week_day' => 1]), new DateTimeImmutable('2026-08-01 03:00', $tz)), '2026-08-03 02:00');
$expectTime('monthly next month', ua_backup_next_run($settings(['frequency' => 'monthly', 'month_day' => 1]), new DateTimeImmutable('2026-08-01 03:00', $tz)), '2026-09-01 02:00');

$expectBool('daily due', ua_backup_is_due($settings(['frequency' => 'daily', 'last_run_at' => '2026-07-31 02:05:00']), new DateTimeImmutable('2026-08-01 03:00', $tz)), true);
$expectBool('daily already ran', ua_backup_is_due($settings(['frequency' => 'daily', 'last_run_at' => '2026-08-01 02:05:00']), new DateTimeImmutable('2026-08-01 03:00', $tz)), false);
$expectBool('weekly due', ua_backup_is_due($settings(['frequency' => 'weekly', 'week_day' => 1, 'last_run_at' => '2026-07-27 02:05:00']), new DateTimeImmutable('2026-08-03 03:00', $tz)), true);
$expectBool('weekly already ran', ua_backup_is_due($settings(['frequency' => 'weekly', 'week_day' => 1, 'last_run_at' => '2026-08-03 02:05:00']), new DateTimeImmutable('2026-08-03 03:00', $tz)), false);
$expectBool('monthly due', ua_backup_is_due($settings(['frequency' => 'monthly', 'month_day' => 1, 'last_run_at' => '2026-07-01 02:05:00']), new DateTimeImmutable('2026-08-01 03:00', $tz)), true);
$expectBool('monthly already ran', ua_backup_is_due($settings(['frequency' => 'monthly', 'month_day' => 1, 'last_run_at' => '2026-08-01 02:05:00']), new DateTimeImmutable('2026-08-01 03:00', $tz)), false);

if ($failures) {
    fwrite(STDERR, implode(PHP_EOL, $failures) . PHP_EOL);
    exit(1);
}

echo "backup_schedule_test: ok\n";
