<?php

namespace Daylight\Core\Http\Controllers\API;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Lang;

class TranslationsController
{
    public function __invoke(?string $locale = null): JsonResponse
    {
        $locale = $locale ?: app()->getLocale();
        $groups = (array) config('daylight.translations.groups', ['general']);

        $messages = Cache::remember("daylight:translations:v5:{$locale}", 3600, function () use ($groups, $locale) {
            $allMessages = [];

            foreach ($groups as $group) {
                $current = (array) Lang::get("daylight::{$group}", [], $locale);

                $dotted = Arr::dot($current);
                foreach ($dotted as $key => $value) {
                    $allMessages["daylight::{$group}.{$key}"] = $value;
                }
            }

            $fallbackLocale = config('app.fallback_locale');
            if ($fallbackLocale && $fallbackLocale !== $locale) {
                foreach ($groups as $group) {
                    $fallback = Arr::dot((array) Lang::get("daylight::{$group}", [], $fallbackLocale));
                    foreach ($fallback as $key => $value) {
                        if (! array_key_exists("daylight::{$group}.{$key}", $allMessages)) {
                            $allMessages["daylight::{$group}.{$key}"] = $value;
                        }
                    }
                }
            }

            return $allMessages;
        });

        return response()->json([
            'locale' => $locale,
            'messages' => $messages,
        ]);
    }
}
