<?php

declare(strict_types=1);

namespace App\Support;

use App\Models\DberpSystemProfile;
use Illuminate\Support\Facades\Schema;

/**
 * 产品对外品牌名：未授权固定默认名；已授权可读系统档案与配置。
 */
final class DberpProductBranding
{
    public function __construct(
        private readonly DberpCommercialLicense $commercialLicense,
    ) {}

    public function defaultBrandName(): string
    {
        $name = config('dberp.product.default_brand_name');

        if (is_string($name) && trim($name) !== '') {
            return trim($name);
        }

        return (string) config('dberp.version.installer_title_base', 'DBErp 进销存系统');
    }

    public function canCustomizeDisplayName(): bool
    {
        return $this->commercialLicense->isGranted();
    }

    public function displayName(): string
    {
        if (! $this->canCustomizeDisplayName()) {
            return $this->defaultBrandName();
        }

        return $this->resolvedLicensedDisplayName();
    }

    /**
     * 登录页左下角：未授权或仍使用默认产品名时展示官网链接与版本；已授权且改为自定义名称时仅展示 © 与名称。
     */
    public function showsOfficialLoginFooterBranding(): bool
    {
        if (! $this->canCustomizeDisplayName()) {
            return true;
        }

        return $this->displayName() === $this->defaultBrandName();
    }

    private function resolvedLicensedDisplayName(): string
    {
        $publicOverride = config('dberp.public_product.name');
        if (is_string($publicOverride) && trim($publicOverride) !== '') {
            return trim($publicOverride);
        }

        if (Schema::hasTable('dberp_system_profile')) {
            $fromDatabase = DberpSystemProfile::query()->value('system_display_name');
            if (is_string($fromDatabase) && trim($fromDatabase) !== '') {
                return trim($fromDatabase);
            }
        }

        $fromEnv = config('dberp.product.name');
        if (is_string($fromEnv) && trim($fromEnv) !== '') {
            return trim($fromEnv);
        }

        return $this->defaultBrandName();
    }
}
