<?php

declare(strict_types=1);

namespace app\common\service;

use app\admin\model\split\Number;
use app\admin\model\split\Ticket;

/**
 * 落地页访问侧下号比率规则：更新连续无进线点击 streak，触线时仅降权（ratio_deferred），不关闭 status
 *
 * 最终关号由同步后 SplitTicketRuleService::applyNumberRules 裁决。
 */
class SplitNumberVisitRuleService
{
    private SplitNumberRatioDeferredService $ratioDeferredService;

    public function __construct(?SplitNumberRatioDeferredService $ratioDeferredService = null)
    {
        $this->ratioDeferredService = $ratioDeferredService ?? new SplitNumberRatioDeferredService();
    }

    /**
     * 访问计数已递增后调用：累加 streak，达到 assign_ratio 时标记 ratio_deferred=1
     */
    public function recordVisitAfterRedirect(int $numberId): void
    {
        if ($numberId <= 0) {
            return;
        }

        /** @var Number|null $number */
        $number = Number::get($numberId);
        if ($number === null) {
            return;
        }

        /** @var Ticket|null $ticket */
        $ticket = Ticket::where('admin_id', (int) $number['admin_id'])
            ->where('split_link_id', (int) $number['split_link_id'])
            ->where('ticket_name', (string) $number['ticket_name'])
            ->find();
        if ($ticket === null) {
            return;
        }

        $assignRatio = (int) ($ticket['assign_ratio'] ?? 0);
        $streak = (int) ($number['no_inbound_click_streak'] ?? 0);
        $hasBaseline = $this->ratioDeferredService->hasLandingVisitBaseline($number);

        if ($hasBaseline) {
            $streak = $this->ratioDeferredService->computeStreakForVisit($number, $streak);
        }

        $update = [
            'no_inbound_click_streak' => $streak,
            'updatetime'              => time(),
        ];

        if ((int) $number['manual_manage'] === 0
            && $this->ratioDeferredService->shouldMarkDeferred($streak, $assignRatio, $hasBaseline)
        ) {
            $update['ratio_deferred'] = 1;
            $update['ratio_deferred_at'] = time();
        }

        Number::where('id', $numberId)->update($update);
    }
}
