<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\LicenseLog;
use App\Models\License;
use Symfony\Component\HttpFoundation\Response;

class ApiTrackingMiddleware
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        // Only track API license verification requests
        if ($request->is('api/license/verify') && $request->isMethod('post')) {
            $this->trackApiCall($request, $response);
        }

        return $response;
    }

    /**
     * Track API call details.
     */
    private function trackApiCall(Request $request, Response $response)
    {
        try {
            $requestData = $request->all();
            $responseData = json_decode($response->getContent(), true) ?? [];

            // Extract license information
            $licenseKey = $requestData['license_key'] ?? null;
            $domain = $requestData['domain'] ?? null;

            // Find license by key
            $license = null;
            if ($licenseKey) {
                $license = License::where('license_key', $licenseKey)->first();
            }

            // Determine status
            $status = 'error';
            if ($response->getStatusCode() === 200 && isset($responseData['success']) && $responseData['success']) {
                $status = 'success';
            } elseif ($response->getStatusCode() >= 400) {
                $status = 'failed';
            }

            // Create log entry
            LicenseLog::create([
                'license_id' => $license ? $license->id : null,
                'domain' => $domain,
                'ip_address' => $request->ip(),
                'serial' => $requestData['serial'] ?? null,
                'status' => $status,
                'user_agent' => $request->userAgent(),
                'request_data' => $requestData,
                'response_data' => $responseData,
            ]);

        } catch (\Exception $e) {
            // Log error but don't break the response
            // API Tracking Error
        }
    }
}