<?php

namespace App\Models;

use Database\Factories\SettingFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

/**
 * @method static updateOrCreate(array<string, string> $array, array<string, mixed> $array1)
 * @method static create(array<string, string> $array)
 * @method static where(string $string, string $key)
 */
class Setting extends Model
{
    /** @use HasFactory<SettingFactory> */
    use HasFactory;

    protected $fillable = ['key', 'value'];

    public static function get(string $key, mixed $default = null): mixed
    {
        $setting = static::where('key', $key)->first();

        return $setting ? $setting->value : $default;
    }

    public static function set(string $key, mixed $value): void
    {
        static::updateOrCreate(['key' => $key], ['value' => $value]);
    }

    public static function getBool(string $key, bool $default = false): bool
    {
        $value = static::get($key, $default);

        return filter_var($value, FILTER_VALIDATE_BOOLEAN);
    }

    public static function setBool(string $key, bool $value): void
    {
        static::set($key, $value ? '1' : '0');
    }

    public static function isArticleProcessingEnabled(): bool
    {
        return static::getBool('article_processing_enabled', true);
    }

    public static function setArticleProcessingEnabled(bool $enabled): void
    {
        static::setBool('article_processing_enabled', $enabled);
    }

    public static function isPublishingApprovalsEnabled(): bool
    {
        return static::getBool('enable_publishing_approvals', true);
    }

    public static function setPublishingApprovalsEnabled(bool $enabled): void
    {
        static::setBool('enable_publishing_approvals', $enabled);
    }

    public static function getArticlePublishingInterval(): int
    {
        return (int) static::get('article_publishing_interval', 5);
    }

    public static function setArticlePublishingInterval(int $minutes): void
    {
        static::set('article_publishing_interval', (string) $minutes);
    }

    public static function getFeedStalenessThreshold(): int
    {
        return (int) static::get('feed_staleness_threshold', 48);
    }

    public static function setFeedStalenessThreshold(int $hours): void
    {
        static::set('feed_staleness_threshold', (string) $hours);
    }

    public static function getDailyPublishCap(): int
    {
        return (int) static::get('daily_publish_cap', 0);
    }

    public static function setDailyPublishCap(int $articles): void
    {
        static::set('daily_publish_cap', (string) $articles);
    }
}
