<?php

declare(strict_types=1);

namespace App\Blog\Support;

use App\Models\Setting;

/**
 * 社交账号聚合：后台「社交账号」Tab 配置 -> 前端展示 + SEO sameAs。
 */
class SocialLinks
{
    public const PLATFORMS = [
        'social_weibo' => '微博',
        'social_zhihu' => '知乎',
        'social_bilibili' => '哔哩哔哩',
        'social_xiaohongshu' => '小红书',
        'social_douyin' => '抖音',
        'social_wechat_channel' => '视频号',
        'social_wechat_public' => '微信公众号',
        'social_github' => 'GitHub',
        'social_twitter' => 'Twitter / X',
        'social_facebook' => 'Facebook',
        'social_email' => '邮箱',
    ];

    /**
     * 全部社交账号：['platform' => 平台名, 'value' => URL/名称, 'url' => 是否为外链]。
     */
    public static function all(): array
    {
        $items = [];

        foreach (self::PLATFORMS as $key => $platform) {
            $value = trim((string) Setting::get($key, ''));
            if ($value === '') {
                continue;
            }
            $items[] = [
                'platform' => $platform,
                'value' => $value,
                'url' => filter_var($value, FILTER_VALIDATE_URL) ? $value : null,
            ];
        }

        // 其他平台（KeyValue）
        $other = Setting::get('social_other', []);
        $other = is_array($other) ? $other : (json_decode((string) $other, true) ?: []);
        foreach ($other as $platform => $value) {
            if (trim((string) $value) === '') {
                continue;
            }
            $items[] = [
                'platform' => (string) $platform,
                'value' => (string) $value,
                'url' => filter_var((string) $value, FILTER_VALIDATE_URL) ? (string) $value : null,
            ];
        }

        return $items;
    }

    /**
     * 可进 JSON-LD sameAs 的 URL 列表。
     */
    public static function sameAs(): array
    {
        return array_values(array_unique(array_filter(array_map(
            fn (array $item) => $item['url'],
            self::all()
        ))));
    }
}
