<?php

namespace App\Services;

use App\Jobs\TrackSearchJob;
use App\Jobs\TrackContentSelectionJob;
use App\Jobs\TrackExportJob;
use App\Jobs\UpdateExportStatusJob;
use Carbon\Carbon;

class TrackingAnalyticsService
{
    /**
     * Track a search action
     */
    public function trackSearch(
        string $deviceId,
        string $searchType,
        string $searchQuery,
        ?array $searchFilters = null,
        ?Carbon $actionAt = null,
        ?string $userAgent = null,
        ?string $ipAddress = null,
        string $platform = 'web'
    ): void {
        TrackSearchJob::dispatch(
            $deviceId,
            $searchType,
            $searchQuery,
            $searchFilters,
            $actionAt ?? now(),
            $userAgent,
            $ipAddress,
            $platform
        );
    }

    /**
     * Track a content selection action
     */
    public function trackContentSelection(
        string $deviceId,
        string $contentType,
        int $contentId,
        string $contentName,
        string $selectionMethod,
        ?string $searchQuery = null,
        ?Carbon $actionAt = null,
        ?string $userAgent = null,
        ?string $ipAddress = null,
        string $platform = 'web'
    ): void {
        TrackContentSelectionJob::dispatch(
            $deviceId,
            $contentType,
            $contentId,
            $contentName,
            $selectionMethod,
            $searchQuery,
            $actionAt ?? now(),
            $userAgent,
            $ipAddress,
            $platform
        );
    }

    /**
     * Track an export action
     */
    public function trackExport(
        string $deviceId,
        ?int $memeId,
        ?int $memeMediaId,
        ?int $backgroundMediaId,
        array $captionTexts,
        string $exportFormat,
        string $exportQuality = 'standard',
        ?Carbon $actionAt = null,
        ?string $userAgent = null,
        ?string $ipAddress = null,
        string $platform = 'web'
    ): int {
        return TrackExportJob::dispatchSync(
            $deviceId,
            $memeId,
            $memeMediaId,
            $backgroundMediaId,
            $captionTexts,
            $exportFormat,
            $exportQuality,
            $actionAt ?? now(),
            $userAgent,
            $ipAddress,
            $platform
        );
    }

    /**
     * Update export status
     */
    public function updateExportStatus(
        int $trackingExportId,
        string $status,
        ?string $errorMessage = null,
        ?Carbon $completedAt = null
    ): void {
        UpdateExportStatusJob::dispatch(
            $trackingExportId,
            $status,
            $errorMessage,
            $completedAt
        );
    }

    /**
     * Get device context from request
     */
    public function getDeviceContext(): array
    {
        $request = request();
        
        return [
            'user_agent' => $request->userAgent(),
            'ip_address' => $request->ip(),
            'platform' => 'web', // Default for now, can be enhanced for mobile detection
        ];
    }

    /**
     * Generate a device ID from request
     */
    public function generateDeviceId(): string
    {
        $request = request();
        
        // Generate a consistent device ID based on session or create new one
        if ($request->session()->has('device_id')) {
            return $request->session()->get('device_id');
        }
        
        $deviceId = str()->uuid()->toString();
        $request->session()->put('device_id', $deviceId);
        
        return $deviceId;
    }

    /**
     * Quick track methods with auto device context
     */
    public function quickTrackSearch(string $searchType, string $searchQuery, ?array $searchFilters = null): void
    {
        $context = $this->getDeviceContext();
        $deviceId = $this->generateDeviceId();
        
        $this->trackSearch(
            $deviceId,
            $searchType,
            $searchQuery,
            $searchFilters,
            null,
            $context['user_agent'],
            $context['ip_address'],
            $context['platform']
        );
    }

    public function quickTrackContentSelection(string $contentType, int $contentId, string $contentName, string $selectionMethod, ?string $searchQuery = null): void
    {
        $context = $this->getDeviceContext();
        $deviceId = $this->generateDeviceId();
        
        $this->trackContentSelection(
            $deviceId,
            $contentType,
            $contentId,
            $contentName,
            $selectionMethod,
            $searchQuery,
            null,
            $context['user_agent'],
            $context['ip_address'],
            $context['platform']
        );
    }

    public function quickTrackExport(?int $memeId, ?int $memeMediaId, ?int $backgroundMediaId, array $captionTexts, string $exportFormat, string $exportQuality = 'standard'): int
    {
        $context = $this->getDeviceContext();
        $deviceId = $this->generateDeviceId();
        
        return $this->trackExport(
            $deviceId,
            $memeId,
            $memeMediaId,
            $backgroundMediaId,
            $captionTexts,
            $exportFormat,
            $exportQuality,
            null,
            $context['user_agent'],
            $context['ip_address'],
            $context['platform']
        );
    }
}