<?php

namespace App\Jobs;

use App\Game\Services\FacebookEventService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class FacebookServerEvent implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected string $eventName;
    protected string $eventId;
    protected $userId;
    protected $value;
    protected ?string $currency;
    protected array $extraCustomData;
    protected string $pixelId;
    protected string $accessToken;

    public $tries = 3;
    public $timeout = 30;

    /**
     * @param string $eventName
     * @param string $eventId
     * @param int|string $userId
     * @param float|int|null $value
     * @param string|null $currency
     * @param string $pixelId
     * @param string $accessToken
     * @param array $extraCustomData
     */
    public function __construct(
        string $eventName,
        string $eventId,
        $userId,
        $value = null,
        ?string $currency = null,
        string $pixelId = '',
        string $accessToken = '',
        array $extraCustomData = []
    ) {
        $this->eventName = $eventName;
        $this->eventId = $eventId;
        $this->userId = $userId;
        $this->value = $value;
        $this->currency = $currency;
        $this->extraCustomData = $extraCustomData;
        $this->pixelId = $pixelId;
        $this->accessToken = $accessToken;
    }

    public function handle(): void
    {
        try {
            // 队列里没有 Request，上报时不依赖 Request，只依赖渠道配置中的 PixelID
            FacebookEventService::trackEvent(
                $this->eventName,
                $this->eventId,
                $this->userId,
                $this->value,
                $this->currency,
                $this->pixelId,
                $this->accessToken,
                $this->extraCustomData
            );
        } catch (\Throwable $e) {
            Log::error('FacebookServerEvent job error', [
                'event_name' => $this->eventName,
                'event_id'   => $this->eventId,
                'user_id'    => $this->userId,
                'message'    => $e->getMessage(),
            ]);
        }
    }
}

