<?php
namespace Tests\Unit\Domain\Update;

use PHPUnit\Framework\TestCase;
use Domain\Update\UpdateRepository;

class UpdateRepositoryTest extends TestCase
{
    private function createMockDb(): \medoo
    {
        return $this->createMock(\medoo::class);
    }

    public function testConstructorAcceptsDb(): void
    {
        $db = $this->createMockDb();
        $repository = new UpdateRepository($db);
        $this->assertInstanceOf(UpdateRepository::class, $repository);
    }

    public function testHasUpdateMethod(): void
    {
        $db = $this->createMockDb();
        $repository = new UpdateRepository($db);
        $this->assertTrue(method_exists($repository, 'update'));
    }

    public function testUpdateReturnsArray(): void
    {
        $db = $this->createMockDb();
        $repository = new UpdateRepository($db);

        $reflection = new \ReflectionClass($repository);
        $method = $reflection->getMethod('update');
        $this->assertEquals('array', (string)$method->getReturnType());
    }

    public function testHasRunPendingMigrationsMethod(): void
    {
        $db = $this->createMockDb();
        $repository = new UpdateRepository($db);
        $this->assertTrue(method_exists($repository, 'runPendingMigrations'));
    }

    public function testRunPendingMigrationsWithNoResults(): void
    {
        $db = $this->createMockDb();
        $db->method('select')->willReturn(false);

        $repository = new UpdateRepository($db);
        $repository->runPendingMigrations();

        $this->assertTrue(true);
    }

    public function testHasPrivateHelperMethods(): void
    {
        $reflection = new \ReflectionClass(UpdateRepository::class);

        $privateMethods = [
            'downloadAndApply',
            'downloadAndApplyLegacy',
            'downloadAndApplyWithManifest',
            'downloadManifest',
            'verifyChecksum',
            'createBackup',
            'executeSql',
            'deleteFiles',
            'extractZip',
            'saveLog',
        ];

        foreach ($privateMethods as $methodName) {
            $this->assertTrue(
                $reflection->hasMethod($methodName),
                "Missing private method: {$methodName}"
            );
            $method = $reflection->getMethod($methodName);
            $this->assertTrue(
                $method->isPrivate(),
                "Method {$methodName} should be private"
            );
        }
    }

    public function testVerifyChecksumValidFormat(): void
    {
        $db = $this->createMockDb();
        $repository = new UpdateRepository($db);

        $reflection = new \ReflectionClass($repository);
        $method = $reflection->getMethod('verifyChecksum');
        $method->setAccessible(true);

        // Create a temp file with known content
        $tmpFile = tempnam(sys_get_temp_dir(), 'test_checksum_');
        file_put_contents($tmpFile, 'test content for checksum');

        $expectedHash = hash_file('sha256', $tmpFile);
        $result = $method->invoke($repository, $tmpFile, 'sha256:' . $expectedHash, []);

        $this->assertTrue($result['valid']);
        $this->assertNotEmpty($result['log']);

        @unlink($tmpFile);
    }

    public function testVerifyChecksumInvalidHash(): void
    {
        $db = $this->createMockDb();
        $repository = new UpdateRepository($db);

        $reflection = new \ReflectionClass($repository);
        $method = $reflection->getMethod('verifyChecksum');
        $method->setAccessible(true);

        $tmpFile = tempnam(sys_get_temp_dir(), 'test_checksum_');
        file_put_contents($tmpFile, 'test content');

        $result = $method->invoke($repository, $tmpFile, 'sha256:invalidhash', []);

        $this->assertFalse($result['valid']);

        @unlink($tmpFile);
    }

    public function testVerifyChecksumInvalidFormat(): void
    {
        $db = $this->createMockDb();
        $repository = new UpdateRepository($db);

        $reflection = new \ReflectionClass($repository);
        $method = $reflection->getMethod('verifyChecksum');
        $method->setAccessible(true);

        $result = $method->invoke($repository, '/tmp/nonexistent', 'badformat', []);

        $this->assertFalse($result['valid']);
    }

    public function testCreateBackupWithEmptyManifest(): void
    {
        $db = $this->createMockDb();
        $repository = new UpdateRepository($db);

        $reflection = new \ReflectionClass($repository);
        $method = $reflection->getMethod('createBackup');
        $method->setAccessible(true);

        $manifest = [
            'version' => '0.999',
            'files' => [],
        ];

        $log = $method->invoke($repository, $manifest, []);

        $this->assertIsArray($log);
        $hasBackupInfo = false;
        foreach ($log as $entry) {
            if (strpos($entry, 'Brak plików do backupu') !== false) {
                $hasBackupInfo = true;
            }
        }
        $this->assertTrue($hasBackupInfo);
    }

    public function testDownloadManifestReturnsNullForInvalidUrl(): void
    {
        $db = $this->createMockDb();
        $repository = new UpdateRepository($db);

        $reflection = new \ReflectionClass($repository);
        $method = $reflection->getMethod('downloadManifest');
        $method->setAccessible(true);

        $result = $method->invoke($repository, 'http://invalid.nonexistent.test', '0.999');

        $this->assertNull($result);
    }
}
