<?php

namespace App\Repositories\Eloquent;

use App\Enums\SettingGroup;
use App\Models\Setting;
use App\Repositories\Contracts\SettingRepositoryInterface;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Cache;

/**
 * @extends BaseRepository<Setting>
 */
class SettingRepository extends BaseRepository implements SettingRepositoryInterface
{
    public function __construct(Setting $model)
    {
        parent::__construct($model);
    }

    /**
     * @return Collection<int, Setting>
     */
    public function all(): Collection
    {
        return $this->model->newQuery()
            ->orderBy('group')
            ->orderBy('order_index')
            ->get();
    }

    /**
     * @return array<string, array<string, mixed>>
     */
    public function publicGrouped(): array
    {
        return Cache::remember('site_settings_all', 3600, function () {
            return $this->model->newQuery()
                ->where('is_public', true)
                ->orderBy('group')
                ->orderBy('order_index')
                ->get()
                ->filter(fn (Setting $s) => ! $s->isSensitive())
                ->groupBy(fn (Setting $s) => $s->group->value)
                ->map(fn ($group) => $group->pluck('value', 'key')->all())
                ->all();
        });
    }

    /**
     * @return array<string, mixed>
     */
    public function publicByGroup(SettingGroup $group): array
    {
        return Cache::remember("site_settings_{$group->value}", 3600, function () use ($group) {
            return $this->model->newQuery()
                ->where('group', $group)
                ->where('is_public', true)
                ->orderBy('order_index')
                ->get()
                ->filter(fn (Setting $s) => ! $s->isSensitive())
                ->pluck('value', 'key')
                ->all();
        });
    }

    public function findByKey(string $key): ?Setting
    {
        return $this->model->newQuery()->where('key', $key)->first();
    }

    /**
     * @return Collection<int, Setting>
     */
    public function getByGroup(SettingGroup $group): Collection
    {
        return $this->model->newQuery()
            ->where('group', $group)
            ->orderBy('order_index')
            ->get();
    }

    /**
     * @param  array<string, mixed>  $settings
     */
    public function bulkUpdate(array $settings): void
    {
        foreach ($settings as $dotKey => $value) {
            [$group, $key] = explode('.', $dotKey, 2);

            $this->model->newQuery()
                ->where('group', $group)
                ->where('key', $key)
                ->update(['value' => $value]);
        }

        $this->clearCache();
    }

    public function clearCache(): void
    {
        Cache::forget('site_settings_all');

        foreach (SettingGroup::cases() as $group) {
            Cache::forget("site_settings_{$group->value}");
        }
    }
}
