<?php

namespace App\Repositories;

use App\Models\SystemSetting;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Schema;

class SystemSettingRepository
{
    public function tableExists(): bool
    {
        return Schema::hasTable('system_settings');
    }

    public function all(): Collection
    {
        return SystemSetting::query()->get();
    }

    public function allPublic(): Collection
    {
        return SystemSetting::query()->where('is_public', true)->get();
    }

    public function findByKey(string $key): ?SystemSetting
    {
        return SystemSetting::query()->where('key', $key)->first();
    }

    public function upsert(array $payload): SystemSetting
    {
        /** @var SystemSetting $setting */
        $setting = SystemSetting::query()->updateOrCreate(
            ['key' => $payload['key']],
            [
                'value' => $payload['value'],
                'type' => $payload['type'],
                'group' => $payload['group'],
                'is_public' => $payload['is_public'],
                'description' => $payload['description'] ?? null,
                'created_by' => $payload['created_by'] ?? null,
                'updated_by' => $payload['updated_by'] ?? null,
            ]
        );

        return $setting;
    }
}
