<?php

declare(strict_types=1);

namespace App\Framework\Http\Streaming;

use App\Framework\Http\Range;

final readonly class RangeParser
{
    public static function parseRange(string $rangeHeader, int $fileSize): ?Range
    {
        // Format: "bytes=start-end"
        if (! preg_match('/bytes=(\d*)-(\d*)/', $rangeHeader, $matches)) {
            return null;
        }

        $start = $matches[1] !== '' ? (int)$matches[1] : 0;
        $end = $matches[2] !== '' ? (int)$matches[2] : $fileSize - 1;

        // Validierung
        if ($start >= $fileSize || $end >= $fileSize || $start > $end) {
            return null;
        }

        return new Range($start, $end, $fileSize);
    }

    /**
     * @return Range[]
     */
    public static function parseMultipleRanges(string $rangeHeader, int $fileSize): array
    {
        // Für mehrere Ranges: "bytes=0-499,1000-1499"
        $ranges = [];

        if (preg_match_all('/(\d*)-(\d*)/', $rangeHeader, $matches, PREG_SET_ORDER)) {
            foreach ($matches as $match) {
                $range = self::parseRange("bytes={$match[0]}", $fileSize);
                if ($range !== null) {
                    $ranges[] = $range;
                }
            }
        }

        return $ranges;
    }
}
