<?php

namespace App\Services;

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

class ServiceImageResolver
{
    /**
     * Fixed export filename for the key-visual image. The image bytes are
     * embedded under this name AND referenced by this name inside the .pro file.
     */
    public const KEY_VISUAL_EXPORT_NAME = 'KEY_VISUAL.jpg';

    /**
     * Fixed export filename for the background image. The image bytes are
     * embedded under this name AND referenced by this name inside the .pro file.
     */
    public const BACKGROUND_EXPORT_NAME = 'BACKGROUND.jpg';

    public function keyVisualFor(Service $service): ?string
    {
        return $this->resolve($service->key_visual_filename, 'current_key_visual');
    }

    public function backgroundFor(Service $service): ?string
    {
        return $this->resolve($service->background_filename, 'current_background');
    }

    private function resolve(?string $serviceFilename, string $settingKey): ?string
    {
        if ($serviceFilename !== null && Storage::disk('public')->exists($serviceFilename)) {
            return $serviceFilename;
        }

        $globalFilename = Setting::get($settingKey);

        if ($globalFilename !== null && Storage::disk('public')->exists($globalFilename)) {
            return $globalFilename;
        }

        return null;
    }
}
