<?php

namespace App\Support;

use Illuminate\Http\Request;
use Illuminate\Support\Str;

class CheckoutRequestContext
{
    /**
     * @return array{ip_address?: string|null, device_id?: string|null, user_agent?: string|null}
     */
    public static function fromRequest(Request $request): array
    {
        return array_filter([
            'ip_address' => $request->ip(),
            'device_id' => static::sanitizeDeviceId(
                $request->header('X-Device-Id', $request->input('device_id'))
            ),
            'user_agent' => static::shortenUserAgent($request->userAgent()),
        ], static fn ($value) => $value !== null && $value !== '');
    }

    private static function sanitizeDeviceId(?string $deviceId): ?string
    {
        if (! $deviceId) {
            return null;
        }

        $cleaned = preg_replace('/[^a-zA-Z0-9_-]/', '', $deviceId) ?? '';

        if ($cleaned === '') {
            return null;
        }

        return Str::substr($cleaned, 0, 64);
    }

    private static function shortenUserAgent(?string $userAgent): ?string
    {
        if (! $userAgent) {
            return null;
        }

        if (Str::length($userAgent) > 1024) {
            return Str::substr($userAgent, 0, 1024);
        }

        return $userAgent;
    }
}
