<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    /**
     * Create a new job instance.
     */
    public function __construct(
        public string $eventType,
        public string $mailboxHash,
        public ?string $domainHash = null,
        public array $metadata = [],
        public ?int $userId = null,
        public string $userType = 'guest',
        public ?string $ipAddress = null,
        public ?string $userAgent = null,
    ) {
        $this->onQueue('analytics');
        $this->onConnection('redis');
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        \App\Models\AnalyticsEvent::create([
            'event_type' => $this->eventType,
            'mailbox_hash' => $this->mailboxHash,
            'domain_hash' => $this->domainHash,
            'user_type' => $this->userType,
            'user_id' => $this->userId,
            'ip_address' => $this->ipAddress ?? request()->ip(),
            'user_agent' => $this->userAgent ?? request()->userAgent(),
            'metadata' => $this->metadata,
        ]);
    }
}
