<?php

namespace App\Services\System\Setting;

use App\Models\SystemConfiguration;
use App\Services\Media\MediaService;
use App\Settings\SystemSettings;
use App\Support\Media\MediaPresenter;
use Illuminate\Http\UploadedFile;
use Illuminate\Validation\ValidationException;

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

    public function systemData(): array
    {
        $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,
        ];
    }

    public function updateSystem(array $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();

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

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

        if (isset($validated['login_cover']) && $validated['login_cover'] instanceof UploadedFile) {
            $this->mediaService->replaceSingleFile($configuration, $validated['login_cover'], 'login_cover', 'login-cover');
        }

        $errors = [];

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

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

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

        if ($errors !== []) {
            throw ValidationException::withMessages($errors);
        }
    }
}
