<?php

use FluxCms\Core\Models\CmsMedia;
use FluxCms\Core\Services\CmsContentService;

if (! function_exists('legal_page')) {
    /**
     * Rechtstexte: zuerst CMS (Gruppe „legal“), sonst Lang-Datei b2in_legal.
     *
     * @return array<string, mixed>
     */
    function legal_page(string $key): array
    {
        $fromCms = app(CmsContentService::class)->get('legal.'.$key);

        if (is_array($fromCms) && isset($fromCms['content'])) {
            return $fromCms;
        }

        return trans('b2in_legal.'.$key);
    }
}

if (! function_exists('cms')) {
    /**
     * Resolve a CMS content value by dot-notation key.
     *
     * First segment is the group, rest is the key: "home.hero.title"
     * Falls back to __() if no DB entry exists.
     *
     * @param  array<string, string>  $replace
     */
    function cms(string $key, array $replace = [], ?string $locale = null): mixed
    {
        return app(CmsContentService::class)->get($key, $replace, $locale);
    }
}

if (! function_exists('tcms')) {
    /**
     * Typed CMS – always returns a string.
     *
     * @param  array<string, string>  $replace
     */
    function tcms(string $key, array $replace = [], ?string $locale = null): string
    {
        $text = cms($key, $replace, $locale);

        return is_string($text) ? $text : (string) $text;
    }
}

if (! function_exists('cms_media_url')) {
    /**
     * Resolve a CMS content key (type=image) to a full media URL.
     * Falls back to asset('assets/images/...') if not found in media library.
     */
    function cms_media_url(string $key, string $profile = ''): string
    {
        $filename = cms($key);

        if (! $filename || ! is_string($filename) || $filename === $key) {
            $fallback = str_replace('.', '/', $key);

            return asset('assets/images/'.basename($fallback));
        }

        return media_url($filename, $profile);
    }
}

if (! function_exists('media_url')) {
    /**
     * Resolve a CmsMedia filename to its full storage URL.
     * Uses in-memory cache to avoid repeated DB queries.
     */
    function media_url(?string $filename, string $profile = ''): string
    {
        if (! $filename || $filename === '') {
            return '';
        }

        static $resolved = [];
        $cacheKey = $filename.'|'.$profile;

        if (isset($resolved[$cacheKey])) {
            return $resolved[$cacheKey];
        }

        $media = CmsMedia::where('filename', $filename)->first();

        if (! $media) {
            $resolved[$cacheKey] = asset('assets/images/'.$filename);

            return $resolved[$cacheKey];
        }

        if ($profile && $media->hasConversion($profile)) {
            $resolved[$cacheKey] = $media->getConversionUrl($profile);
        } else {
            $resolved[$cacheKey] = $media->getUrl();
        }

        return $resolved[$cacheKey];
    }
}
