<?php

declare(strict_types=1);

namespace App\Support;

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

/**
 * 登录页备案信息展示：从系统档案读取备案号并生成指向官方平台的固定链接。
 */
final class DberpSiteFilingRecords
{
    public const ICP_PLATFORM_URL = 'https://beian.miit.gov.cn/';

    public const PUBLIC_SECURITY_PLATFORM_HOME_URL = 'https://www.beian.gov.cn/portal/index';

    /** 公安备案号旁展示的官方图标（位于 public/ 目录） */
    public const PUBLIC_SECURITY_ICON_PATH = 'beian.png';

    private const PUBLIC_SECURITY_DETAIL_URL = 'https://www.beian.gov.cn/portal/registerSystemInfo?recordcode=%s';

    public static function normalizeOptionalRecord(?string $value): ?string
    {
        if ($value === null) {
            return null;
        }

        $trimmed = trim($value);

        return $trimmed === '' ? null : $trimmed;
    }

    public static function icpLinkUrl(): string
    {
        return self::ICP_PLATFORM_URL;
    }

    public static function publicSecurityIconUrl(): string
    {
        return asset(self::PUBLIC_SECURITY_ICON_PATH);
    }

    public static function publicSecurityLinkUrl(?string $recordNo): string
    {
        $normalized = self::normalizeOptionalRecord($recordNo);

        if ($normalized === null) {
            return self::PUBLIC_SECURITY_PLATFORM_HOME_URL;
        }

        $recordCode = preg_replace('/\D+/', '', $normalized) ?? '';

        if ($recordCode === '') {
            return self::PUBLIC_SECURITY_PLATFORM_HOME_URL;
        }

        return sprintf(self::PUBLIC_SECURITY_DETAIL_URL, $recordCode);
    }

    public static function icpRecordNo(): ?string
    {
        return self::normalizeOptionalRecord(self::readProfileColumn('site_icp_record_no'));
    }

    public static function publicSecurityRecordNo(): ?string
    {
        return self::normalizeOptionalRecord(self::readProfileColumn('site_public_security_record_no'));
    }

    public static function hasAnyForLoginFooter(): bool
    {
        return self::icpRecordNo() !== null || self::publicSecurityRecordNo() !== null;
    }

    /**
     * @return list<array{text: string, url: string, icon_url: ?string}>
     */
    public static function loginFooterItems(): array
    {
        $items = [];

        $icp = self::icpRecordNo();
        if ($icp !== null) {
            $items[] = [
                'text' => $icp,
                'url' => self::icpLinkUrl(),
                'icon_url' => null,
            ];
        }

        $publicSecurity = self::publicSecurityRecordNo();
        if ($publicSecurity !== null) {
            $items[] = [
                'text' => $publicSecurity,
                'url' => self::publicSecurityLinkUrl($publicSecurity),
                'icon_url' => self::publicSecurityIconUrl(),
            ];
        }

        return $items;
    }

    private static function readProfileColumn(string $column): mixed
    {
        try {
            $table = (new DberpSystemProfile)->getTable();

            if (! Schema::hasTable($table) || ! Schema::hasColumn($table, $column)) {
                return null;
            }

            return DberpSystemProfile::query()->value($column);
        } catch (\Throwable) {
            return null;
        }
    }
}
