<?php

declare(strict_types=1);

namespace Builder\Core\Models;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

/**
 * @property int $id
 * @property string $code
 * @property string $name
 * @property bool $is_active
 * @property bool $is_default
 * @property int $order
 * @property Carbon $created_at
 * @property Carbon $updated_at
 */
final class Language extends Model
{
    public const string CACHE_KEY = 'builder.languages';

    public const int CACHE_TTL = 300;

    protected $fillable = ['code', 'name', 'is_active', 'is_default', 'order'];

    public function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'is_default' => 'boolean',
        ];
    }

    protected static function booted(): void
    {
        self::saved(fn (): bool => Cache::forget(self::CACHE_KEY));
        self::deleted(fn (): bool => Cache::forget(self::CACHE_KEY));
    }

    public static function clearCache(): void
    {
        Cache::forget(self::CACHE_KEY);
    }

    /** @return Collection<int, Language> */
    public static function allLocales(): Collection
    {
        $cached = Cache::get(self::CACHE_KEY);

        if ($cached instanceof Collection) {
            return $cached;
        }

        Cache::forget(self::CACHE_KEY);

        $result = self::orderBy('order')->orderBy('code')->get();
        Cache::put(self::CACHE_KEY, $result, self::CACHE_TTL);

        return $result;
    }

    /** @return Collection<int, Language> */
    public static function activeLocales(): Collection
    {
        return self::allLocales()->where('is_active', true)->values();
    }

    public static function defaultLocale(): self
    {
        return self::allLocales()->firstWhere('is_default', true)
            ?? self::activeLocales()->first()
            ?? throw new \RuntimeException('No default language configured.');
    }
}
