<?php

namespace App\Http\Controllers\Api\V1\Integration;

use App\Http\Controllers\Controller;
use App\Models\AdminSite;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;

/**
 * 玩家端 iframe 运行时白名单。
 *
 * 只公开启用站点的 origin，不包含任何密钥或钱包地址。
 */
final class IntegrationRuntimeOriginsController extends Controller
{
    public function __invoke(): JsonResponse
    {
        $origins = AdminSite::query()
            ->where('status', 1)
            ->pluck('iframe_allowed_origins')
            ->flatMap(static function (mixed $value): array {
                if (is_string($value)) {
                    $decoded = json_decode($value, true);
                    $value = is_array($decoded) ? $decoded : [];
                }

                if (! is_array($value)) {
                    return [];
                }

                return array_values(array_filter(
                    array_map(
                        static fn (mixed $origin): string => is_string($origin) ? trim($origin) : '',
                        $value,
                    ),
                    static fn (string $origin): bool => $origin !== '',
                ));
            })
            ->unique()
            ->values()
            ->all();

        return ApiResponse::success([
            'iframe_allowed_origins' => $origins,
        ]);
    }
}
