<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Spatie\ResponseCache\Hasher\RequestHasher;

class InertiaResponseCacheHasher implements RequestHasher
{
    public function getHashFor(Request $request): string
    {
        $hashParts = [
            $request->getMethod(),
            $request->getPathInfo(),
            $request->getQueryString(),
        ];

        // Include Inertia-specific headers in the hash
        if ($request->header('X-Inertia')) {
            $hashParts[] = 'inertia';

            // Include the Inertia version if present
            if ($version = $request->header('X-Inertia-Version')) {
                $hashParts[] = "version:{$version}";
            }

            // Include partial reload components if present
            if ($partial = $request->header('X-Inertia-Partial-Component')) {
                $hashParts[] = "partial:{$partial}";
            }

            if ($data = $request->header('X-Inertia-Partial-Data')) {
                $hashParts[] = "data:{$data}";
            }
        } else {
            $hashParts[] = 'html';
        }

        // Include user agent for mobile/desktop differences if needed
        // $hashParts[] = $this->getUserAgentHash($request);

        return md5(implode('|', array_filter($hashParts)));
    }

    /**
     * Get a simplified hash of user agent for mobile/desktop caching
     */
    protected function getUserAgentHash(Request $request): string
    {
        $userAgent = $request->userAgent() ?? '';

        // Simple mobile detection
        $isMobile = preg_match('/Mobile|Android|iPhone|iPad/', $userAgent);

        return $isMobile ? 'mobile' : 'desktop';
    }
}
