<?php

namespace app\admin\model\shopro\xhs;

use app\admin\model\shopro\Common;

/**
 * 小红书广告追踪模型
 */
class AdTracking extends Common
{
    protected $name = 'xhs_ad_tracking';

    protected $updateTime = 'updatetime';
    protected $createTime = 'createtime';
    protected $autoWriteTimestamp = 'integer';

    // 30 天归因窗口（秒）
    const ATTRIBUTION_WINDOW = 30 * 86400;

    // 平台来源常量
    const PLATFORM_MINIPROGRAM = 'WechatMiniProgram';

    /**
     * 记录广告追踪信息
     * 同一用户在归因期内多次点击，更新为最新的 click_id
     *
     * @param array $params
     * @return AdTracking|null
     */
    public static function record($params)
    {
        $userId = $params['user_id'] ?? 0;
        $clickId = $params['click_id'] ?? '';
        $platform = $params['platform'] ?? self::PLATFORM_MINIPROGRAM;

        if (empty($userId) || empty($clickId)) {
            return null;
        }

        $now = time();
        $expiresAt = $now + self::ATTRIBUTION_WINDOW;

        // 查询已有记录（未过期）
        $exist = self::where('user_id', $userId)
            ->where('expires_at', '>', $now)
            ->find();

        if ($exist) {
            // 更新为最新 click_id
            $exist->click_id = $clickId;
            $exist->request_id = $params['request_id'] ?? $exist->request_id;
            $exist->event_type = $params['event_type'] ?? $exist->event_type;
            $exist->landing_page = $params['landing_page'] ?? $exist->landing_page;
            $exist->expires_at = $expiresAt;
            $exist->updatetime = $now;
            $exist->save();

            return $exist;
        }

        // 新建记录
        return self::create([
            'user_id'      => $userId,
            'click_id'     => $clickId,
            'request_id'   => $params['request_id'] ?? '',
            'event_type'   => $params['event_type'] ?? '',
            'landing_page' => $params['landing_page'] ?? '',
            'platform'     => $platform,
            'createtime'   => $now,
            'updatetime'   => $now,
            'expires_at'   => $expiresAt,
        ]);
    }

    /**
     * 根据 user_id 获取有效期内的有效 click_id
     *
     * @param int $userId
     * @return AdTracking|null
     */
    public static function getValidByUser($userId)
    {
        $now = time();

        return self::where('user_id', $userId)
            ->where('expires_at', '>', $now)
            ->order('id', 'desc')
            ->find();
    }
}
