<?php

use App\Models\Service;
use App\Models\Setting;
use App\Services\ServiceImageResolver;
use Illuminate\Support\Facades\Storage;

beforeEach(function () {
    Storage::fake('public');
});

test('key visual uses service file when present', function () {
    Storage::disk('public')->put('slides/kv.jpg', 'fake-content');
    Setting::set('current_key_visual', 'slides/global-kv.jpg');

    $service = Service::factory()->create([
        'key_visual_filename' => 'slides/kv.jpg',
    ]);

    expect(app(ServiceImageResolver::class)->keyVisualFor($service))->toBe('slides/kv.jpg');
});

test('key visual falls back to global setting when service value is empty', function () {
    Storage::disk('public')->put('slides/global-kv.jpg', 'fake-content');
    Setting::set('current_key_visual', 'slides/global-kv.jpg');

    $service = Service::factory()->create([
        'key_visual_filename' => null,
    ]);

    expect(app(ServiceImageResolver::class)->keyVisualFor($service))->toBe('slides/global-kv.jpg');
});

test('key visual returns null when service and global values are empty', function () {
    $service = Service::factory()->create([
        'key_visual_filename' => null,
    ]);

    expect(app(ServiceImageResolver::class)->keyVisualFor($service))->toBeNull();
});

test('key visual skips missing service file and falls through to existing global file', function () {
    Storage::disk('public')->put('slides/global-kv.jpg', 'fake-content');
    Setting::set('current_key_visual', 'slides/global-kv.jpg');

    $service = Service::factory()->create([
        'key_visual_filename' => 'slides/kv-missing.jpg',
    ]);

    expect(app(ServiceImageResolver::class)->keyVisualFor($service))->toBe('slides/global-kv.jpg');
});

test('background uses service file falls back to global and returns null when none exist', function () {
    Storage::disk('public')->put('slides/bg.jpg', 'fake-content');
    Setting::set('current_background', 'slides/global-bg.jpg');

    $service = Service::factory()->create([
        'background_filename' => 'slides/bg.jpg',
    ]);

    expect(app(ServiceImageResolver::class)->backgroundFor($service))->toBe('slides/bg.jpg');

    Storage::disk('public')->delete('slides/bg.jpg');
    Storage::disk('public')->put('slides/global-bg.jpg', 'fake-content');
    $service->update(['background_filename' => null]);

    expect(app(ServiceImageResolver::class)->backgroundFor($service->refresh()))->toBe('slides/global-bg.jpg');

    Storage::disk('public')->delete('slides/global-bg.jpg');
    Setting::set('current_background', null);

    expect(app(ServiceImageResolver::class)->backgroundFor($service->refresh()))->toBeNull();
});
