<?php

declare(strict_types=1);

namespace Tests\Framework\DateTime;

use App\Framework\DateTime\SystemClock;

class SystemClockTest extends \PHPUnit\Framework\TestCase
{
    public function testNowReturnsCurrentDateTime(): void
    {
        $clock = new SystemClock();
        $now = $clock->now();

        $this->assertInstanceOf(\DateTimeImmutable::class, $now);
        $this->assertEquals('UTC', $now->getTimezone()->getName());

        // Überprüfen, dass das Datum innerhalb von 2 Sekunden liegt (für Testlaufzeit)
        $this->assertLessThanOrEqual(2, abs(time() - $now->getTimestamp()));
    }

    public function testFromTimestampReturnsCorrectDateTime(): void
    {
        $clock = new SystemClock();
        $timestamp = 1609459200; // 2021-01-01 00:00:00 UTC
        $date = $clock->fromTimestamp($timestamp);

        $this->assertInstanceOf(\DateTimeImmutable::class, $date);
        $this->assertEquals($timestamp, $date->getTimestamp());
        $this->assertEquals('UTC', $date->getTimezone()->getName());
    }

    public function testFromStringReturnsCorrectDateTime(): void
    {
        $clock = new SystemClock();
        $date = $clock->fromString('2021-01-01 00:00:00');

        $this->assertInstanceOf(\DateTimeImmutable::class, $date);
        $this->assertEquals('2021-01-01', $date->format('Y-m-d'));
        $this->assertEquals('00:00:00', $date->format('H:i:s'));
    }

    public function testFromStringWithFormatReturnsCorrectDateTime(): void
    {
        $clock = new SystemClock();
        $date = $clock->fromString('01/01/2021', 'd/m/Y');

        $this->assertInstanceOf(\DateTimeImmutable::class, $date);
        $this->assertEquals('2021-01-01', $date->format('Y-m-d'));
    }

    public function testFromStringWithInvalidFormatThrowsException(): void
    {
        $clock = new SystemClock();

        $this->expectException(\Exception::class);
        $clock->fromString('not a date', 'Y-m-d');
    }

    public function testClockWithCustomTimezone(): void
    {
        $clock = new SystemClock('Europe/Berlin');
        $now = $clock->now();

        $this->assertEquals('Europe/Berlin', $now->getTimezone()->getName());
    }
}
