<?php

namespace NoahVet\Reef\Domain\Http;

use Psr\Http\Message\ResponseInterface;

class CacheHeaderParser
{
    public static function getExpirationDate(ResponseInterface $response): ?\DateTimeImmutable
    {
        $cacheControl = $response->getHeaderLine('Cache-Control');
        if (\str_contains($cacheControl, 'no-cache') || \str_contains($cacheControl, 'no-store')) {
            return null;
        }

        if (\preg_match('#max-age=(?<maxage>[0-9]+)#', $cacheControl, $matchs)) {
            return new \DateTimeImmutable('+'.$matchs['maxage'].' seconds');
        }

        $expires = $response->getHeaderLine('Expires');
        if (!empty($expires)) {
            $expiresDate = \DateTimeImmutable::createFromFormat(\DATE_RFC2822, $expires);
            if ($expiresDate) {
                return $expiresDate;
            }
        }

        return null;
    }
}
