<?php

namespace App\Support;

use App\Models\AppSetting;
use Illuminate\Support\Facades\Cache;

final class ApplicationName
{
    private static ?string $resolved = null;

    private const CACHE_KEY = 'app_name:current:v1';

    private const CACHE_SECONDS = 300;

    public static function current(): string
    {
        if (self::$resolved !== null) {
            return self::$resolved;
        }

        try {
            return self::$resolved = Cache::remember(
                self::CACHE_KEY,
                now()->addSeconds(self::CACHE_SECONDS),
                static function (): string {
                    try {
                        $stored = AppSetting::query()->where('key', 'global')->value('value');
                        if (is_array($stored)) {
                            $name = trim((string) ($stored['app_name'] ?? ''));
                            if ($name !== '') {
                                return $name;
                            }
                        }
                    } catch (\Throwable) {
                        // Missing table, bad JSON, connection loss, etc.
                    }

                    return (string) config('app.name', 'Budgets');
                }
            );
        } catch (\Throwable) {
            return self::$resolved = (string) config('app.name', 'Budgets');
        }
    }

    public static function forget(): void
    {
        self::$resolved = null;
        try {
            Cache::forget(self::CACHE_KEY);
        } catch (\Throwable) {
            // ignore cache backend issues
        }
    }
}
