<?php

declare(strict_types=1);

namespace app\common\service;

use app\admin\model\split\Link;

/**
 * 分流中转页上下文：跳转 URL + 像素渲染
 */
class SplitVisitPageService
{
    /**
     * @return array{
     *   redirect_url: string,
     *   redirect_url_json: string,
     *   pixel_head_html: string,
     *   pixel_body_html: string,
     *   orchestrator_html: string
     * }|null
     */
    public static function build(string $linkCode, string $clientIp, string $userAgent, string $pageUrl): ?array
    {
        $redirectUrl = (new SplitRedirectService())->resolveRedirectUrl($linkCode, $clientIp);
        if ($redirectUrl === null || $redirectUrl === '') {
            return null;
        }

        $link = Link::where('link_code', SplitLinkCodeService::normalize($linkCode))
            ->where('status', 'normal')
            ->field('id,pixel_config')
            ->find();

        $config = SplitPixelConfigService::parseStorage(
            $link ? (string) $link->getAttr('pixel_config') : ''
        );

        SplitPixelPostbackService::dispatch($config, $clientIp, $userAgent, $pageUrl);

        $pixel = SplitPixelBrowserRenderer::render($config);
        $redirectJson = json_encode(
            $redirectUrl,
            JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_SLASHES
        );

        return [
            'redirect_url'      => $redirectUrl,
            'redirect_url_json' => $redirectJson ?: '""',
            'pixel_head_html'   => $pixel['head_html'],
            'pixel_body_html'   => $pixel['body_html'],
            'orchestrator_html' => SplitPixelBrowserRenderer::renderRedirectOrchestrator(
                $redirectJson ?: '""',
                $pixel['track_lines'] ?? []
            ),
        ];
    }
}
