<?php

namespace App\Services\System\Setting;

use App\Models\SystemConfiguration;
use App\Services\Concerns\CachesQuery;
use App\Services\Concerns\RunsInTransaction;
use App\Services\Concerns\SyncsPhotos;
use App\Services\Media\MediaService;
use App\Settings\SystemSettings;
use App\Support\Media\MediaPresenter;
use Illuminate\Validation\ValidationException;

class SystemService
{
    use CachesQuery, RunsInTransaction, SyncsPhotos;

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

    public function systemData(): array
    {
        return $this->cacheRemember('system:settings', 86400, function () {
            $settings = app(SystemSettings::class);
            $configuration = SystemConfiguration::instance();
            $configuration->load('media');

            $logo = MediaPresenter::first($configuration, 'logo');
            $favicon = MediaPresenter::first($configuration, 'favicon');
            $loginCover = MediaPresenter::first($configuration, 'login_cover');

            return [
                'app_name' => $settings->app_name,
                'about_app' => $settings->about_app,
                'email' => $settings->email,
                'phone' => $settings->phone,
                'address' => $settings->address,
                'logo_url' => $logo['url'] ?? null,
                'favicon_url' => $favicon['url'] ?? null,
                'login_cover_url' => $loginCover['url'] ?? null,
                'logo' => $logo,
                'favicon' => $favicon,
                'login_cover' => $loginCover,
            ];
        });
    }

    public function updateSystem(array $validated): void
    {
        $this->runInTransaction(
            function () use ($validated): void {
                $settings = app(SystemSettings::class);
                $configuration = SystemConfiguration::instance();

                $settings->app_name = $validated['app_name'];
                $settings->about_app = $validated['about_app'] ?? null;
                $settings->email = $validated['email'] ?? null;
                $settings->phone = $validated['phone'] ?? null;
                $settings->address = $validated['address'] ?? null;
                $settings->save();

                $hasLogoInput = isset($validated['logo']) || isset($validated['logo_s3_key']);
                $hasFaviconInput = isset($validated['favicon']) || isset($validated['favicon_s3_key']);
                $hasLoginCoverInput = isset($validated['login_cover']) || isset($validated['login_cover_s3_key']);

                $this->syncPhotos(
                    $configuration,
                    [
                        'photos' => isset($validated['logo']) ? [$validated['logo']] : null,
                        's3_keys' => isset($validated['logo_s3_key']) ? [$validated['logo_s3_key']] : null,
                    ],
                    maxPhotos: 1,
                    required: false,
                    collection: 'logo',
                );

                $this->syncPhotos(
                    $configuration,
                    [
                        'photos' => isset($validated['favicon']) ? [$validated['favicon']] : null,
                        's3_keys' => isset($validated['favicon_s3_key']) ? [$validated['favicon_s3_key']] : null,
                    ],
                    maxPhotos: 1,
                    required: false,
                    collection: 'favicon',
                );

                $this->syncPhotos(
                    $configuration,
                    [
                        'photos' => isset($validated['login_cover']) ? [$validated['login_cover']] : null,
                        's3_keys' => isset($validated['login_cover_s3_key']) ? [$validated['login_cover_s3_key']] : null,
                    ],
                    maxPhotos: 1,
                    required: false,
                    collection: 'login_cover',
                );

                $errors = [];

                if ($hasLogoInput && ! $configuration->hasMedia('logo')) {
                    $errors['logo'] = 'Logo wajib diisi.';
                }

                if ($hasFaviconInput && ! $configuration->hasMedia('favicon')) {
                    $errors['favicon'] = 'Favicon wajib diisi.';
                }

                if ($hasLoginCoverInput && ! $configuration->hasMedia('login_cover')) {
                    $errors['login_cover'] = 'Cover login wajib diisi.';
                }

                if ($errors !== []) {
                    throw ValidationException::withMessages($errors);
                }
            },
            'Gagal memperbarui pengaturan sistem',
        );

        $this->cacheForget('system:settings');
        $this->cacheForget('homepage:page_data');
    }
}
