<?php

namespace Tests\Unit;

use App\Facades\Settings;
use App\Traits\ResolvesSiteFavicon;
use Illuminate\Support\Facades\Storage;
use Mtc\MercuryDataModels\Tenant;
use Tests\TestCase;

class ResolvesSiteFaviconTest extends TestCase
{
    private object $resolver;

    protected function setUp(): void
    {
        parent::setUp();

        Storage::fake('media');
        config(['filesystems.default_media' => 'media']);

        $this->resolver = new class () {
            use ResolvesSiteFavicon;

            public function resolve(Tenant $site): array
            {
                return $this->resolveSiteFavicon($site);
            }
        };
    }

    private function tenant(string $name = 'Test Site'): Tenant
    {
        $tenant = new Tenant();
        $tenant->name = $name;

        return $tenant;
    }

    public function testReturnsFaviconWhenTheFileExistsOnTheMediaDisk(): void
    {
        $path = 'test_site/assets/favicon.ico';
        Storage::disk('media')->put($path, 'icon-bytes');

        Settings::shouldReceive('get')
            ->with('site-favicon')
            ->andReturn(['path' => $path, 'url' => 'https://cdn.example.com/' . $path]);

        $icon = $this->resolver->resolve($this->tenant());

        $this->assertSame('https://cdn.example.com/' . $path, $icon['url']);
        $this->assertSame($path, $icon['path']);
    }

    public function testFallsBackToPlaceholderWhenTheFaviconFileIsMissing(): void
    {
        Settings::shouldReceive('get')
            ->with('site-favicon')
            ->andReturn(['path' => 'test_site/assets/favicon.ico', 'url' => 'https://cdn.example.com/missing.ico']);

        $icon = $this->resolver->resolve($this->tenant('Acme Cars'));

        $this->assertStringStartsWith('https://ui-avatars.com/api/?name=Acme+Cars', $icon['url']);
        $this->assertArrayNotHasKey('path', $icon);
    }

    public function testFallsBackToPlaceholderWhenNoFaviconIsSaved(): void
    {
        Settings::shouldReceive('get')
            ->with('site-favicon')
            ->andReturn(null);

        $icon = $this->resolver->resolve($this->tenant('Acme Cars'));

        $this->assertStringStartsWith('https://ui-avatars.com/api/?name=Acme+Cars', $icon['url']);
    }

    public function testFallsBackToPlaceholderWhenReadingTheSettingThrows(): void
    {
        Settings::shouldReceive('get')
            ->with('site-favicon')
            ->andThrow(new \RuntimeException('The MAC is invalid.'));

        $icon = $this->resolver->resolve($this->tenant('Acme Cars'));

        $this->assertStringStartsWith('https://ui-avatars.com/api/?name=Acme+Cars', $icon['url']);
    }
}
