<?php

namespace App\Domain\Shared\Services;

use App\Domain\Shared\Models\SystemSetting;
use Illuminate\Support\Collection;

class SettingsService
{
    public function get(string $key, $default = null)
    {
        $academyId = app()->has('current_academy') ? app('current_academy')->id : null;
        if (!$academyId) {
            return $default;
        }

        $setting = SystemSetting::withoutGlobalScope('academy')
            ->where('academy_id', $academyId)
            ->where('key', $key)
            ->first();

        if (!$setting) {
            return $default;
        }

        return $setting->castValue();
    }

    public function set(string $key, $value, string $group = 'general', ?string $type = null): void
    {
        $academyId = app()->has('current_academy') ? app('current_academy')->id : null;
        if (!$academyId) {
            return;
        }

        SystemSetting::withoutGlobalScope('academy')->updateOrCreate(
            ['academy_id' => $academyId, 'key' => $key],
            [
                'value' => is_array($value) ? json_encode($value) : (string) $value,
                'group' => $group,
                'type' => $type ?? 'string',
            ]
        );
    }

    public function getGroup(string $group): array
    {
        $academyId = app()->has('current_academy') ? app('current_academy')->id : null;
        if (!$academyId) {
            return [];
        }

        return SystemSetting::withoutGlobalScope('academy')
            ->where('academy_id', $academyId)
            ->where('group', $group)
            ->get()
            ->mapWithKeys(fn ($s) => [$s->key => $s->castValue()])
            ->toArray();
    }

    public function getAll(): Collection
    {
        $academyId = app()->has('current_academy') ? app('current_academy')->id : null;
        if (!$academyId) {
            return collect();
        }

        return SystemSetting::withoutGlobalScope('academy')
            ->where('academy_id', $academyId)
            ->get();
    }
}
