<?php

namespace App\Services\System\Setting;

use App\Models\HomepageConfiguration;
use App\Services\Media\MediaService;
use App\Support\Media\MediaPresenter;
use Illuminate\Http\UploadedFile;

class HomepageSettingService
{
    public function __construct(
        private readonly MediaService $mediaService,
    ) {}

    public function homepageData(): array
    {
        $configuration = HomepageConfiguration::instance();
        $configuration->load('media');

        $heroImage = MediaPresenter::first($configuration, 'hero_image');
        $aboutImage = MediaPresenter::first($configuration, 'about_image');
        $galleryImages = MediaPresenter::collection($configuration, 'gallery');

        return [
            'hero_image_url' => $heroImage['url'] ?? null,
            'about_image_url' => $aboutImage['url'] ?? null,
            'gallery_images' => $galleryImages,
        ];
    }

    public function updateHomepage(array $validated): void
    {
        $configuration = HomepageConfiguration::instance();

        if (isset($validated['hero_image']) && $validated['hero_image'] instanceof UploadedFile) {
            $this->mediaService->replaceSingleFile($configuration, $validated['hero_image'], 'hero_image', 'hero-image');
        }

        if (isset($validated['about_image']) && $validated['about_image'] instanceof UploadedFile) {
            $this->mediaService->replaceSingleFile($configuration, $validated['about_image'], 'about_image', 'about-image');
        }

        if (isset($validated['gallery_images']) || isset($validated['gallery_images_remove'])) {
            $this->mediaService->syncCollection(
                $configuration,
                'gallery',
                $validated['gallery_images'] ?? [],
                $validated['gallery_images_remove'] ?? [],
                10,
                'gallery',
            );
        }
    }
}
