<?php

namespace App\Domains\Translation\Providers;

use App\Domains\Translation\Models\Translation;
use Illuminate\Contracts\Translation\Loader;
use Illuminate\Support\Facades\Redis;

class DatabaseTranslationLoader implements Loader
{
    /** @return array<string, string> */
    public function load($locale, $group, $namespace = null): array
    {
        $ns = $namespace ?? '*';
        $cacheKey = "lang:{$ns}:{$locale}:{$group}";

        $cached = Redis::hGetAll($cacheKey);
        if (! empty($cached)) {
            return $cached;
        }

        $translations = Translation::where('locale', $locale)
            ->where('group', $group)
            ->where('namespace', $namespace ?? '*')
            ->pluck('value', 'key')
            ->toArray();

        if (! empty($translations)) {
            Redis::hMSet($cacheKey, $translations);
            Redis::expire($cacheKey, 3600);
        }

        return $translations;
    }

    public function addNamespace($namespace, $hint): void {}

    public function addJsonPath($path): void {}

    /** @return array<string, string> */
    public function namespaces(): array
    {
        return [];
    }
}
