<?php

namespace MintyPHP\Tests\Module\Security\Service;

use MintyPHP\Module\Security\Service\SecurityReportLogoService;
use PHPUnit\Framework\TestCase;

/**
 * Service-behaviour test. As with TenantLogoServiceTest, the successful upload
 * path is asserted indirectly (MIME/size guards, no directory creation on
 * rejection) because move_uploaded_file() needs a real HTTP-uploaded file and
 * cannot run under phpunit. The move step is covered by manual smoke testing.
 */
class SecurityReportLogoServiceTest extends TestCase
{
    private SecurityReportLogoService $service;

    protected function setUp(): void
    {
        $this->service = new SecurityReportLogoService();
    }

    public function testReportLogoDirIsScopedToSecurityReportLogo(): void
    {
        $this->assertStringEndsWith('/security/report-logo', $this->service->reportLogoDir());
    }

    public function testSaveUploadRejectsMissingFile(): void
    {
        $this->assertFalse($this->service->saveUpload([])['ok']);
    }

    public function testSaveUploadRejectsUploadError(): void
    {
        $result = $this->service->saveUpload([
            'tmp_name' => '/tmp/whatever',
            'error' => UPLOAD_ERR_NO_FILE,
            'size' => 100,
        ]);

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

    public function testSaveUploadRejectsOversizedFile(): void
    {
        $result = $this->service->saveUpload([
            'tmp_name' => '/tmp/whatever',
            'error' => UPLOAD_ERR_OK,
            'size' => 6 * 1024 * 1024,
        ]);

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

    public function testSaveUploadRejectsNonImageContent(): void
    {
        $tmp = tempnam(sys_get_temp_dir(), 'sec-logo-test');
        $this->assertNotFalse($tmp);
        file_put_contents($tmp, "just some plain text, not an image\n");

        try {
            $result = $this->service->saveUpload([
                'tmp_name' => $tmp,
                'error' => UPLOAD_ERR_OK,
                'size' => filesize($tmp),
            ]);

            $this->assertFalse($result['ok']);
            // Rejection must happen before any directory/file is created.
            $this->assertFalse(is_dir($this->service->reportLogoDir() . '/__never__'));
        } finally {
            @unlink($tmp);
        }
    }

    public function testDeleteIsIdempotentWhenNothingStored(): void
    {
        // delete() is safe to call even when the directory does not exist.
        $this->assertTrue($this->service->delete());
    }
}
