<?php

declare(strict_types=1);

namespace App\Framework\Analytics\Middleware;

use App\Framework\Analytics\AnalyticsInterface;
use App\Framework\Analytics\AnalyticsService;
use App\Framework\Config\Configuration;
use App\Framework\Context\ExecutionContext;
use App\Framework\Http\HttpMiddleware;
use App\Framework\Http\MiddlewareContext;
use App\Framework\Http\MiddlewarePriority;
use App\Framework\Http\MiddlewarePriorityAttribute;
use App\Framework\Http\RequestStateManager;
use App\Framework\Performance\PerformanceMeter;
use App\Framework\Queue\FileQueue;

#[MiddlewarePriorityAttribute(MiddlewarePriority::BUSINESS_LOGIC)]
final readonly class AnalyticsMiddleware implements HttpMiddleware
{
    private AnalyticsService $analytics;
    public function __construct(
        #private AnalyticsInterface $analytics = new AnalyticsService($queue, $executionContext, $config),
        private ExecutionContext $executionContext,
        private Configuration $config,
        private PerformanceMeter $performanceMeter
    ) {
        $this->analytics = new AnalyticsService(new FileQueue(__DIR__.'/analytics-data'), $this->executionContext, $this->config);
    }

    public function __invoke(MiddlewareContext $context, callable $next, RequestStateManager $stateManager): MiddlewareContext
    {
        $startTime = microtime(true);


        $request = $context->request;

        // Track page view
        /*$this->analytics->trackPageView(
            $context->request->path,
            [
                'method' => $request->method->value,
                'query_params' => $request->queryParams,
                'referer' => $request->headers->get('Referer')
            ]
        );*/

        $context = $next($context);

        // Track response performance
        $responseTime = (microtime(true) - $startTime) * 1000;

        /*$this->analytics->trackPerformance('response_time', $responseTime, [
            'path' => $request->path,
            'method' => $request->method->value,
            'status_code' => $context->response->status->value
        ]);*/

        return $context;
    }
}
