<?php
/**
 * Click analytics retention policy.
 *
 * @package Affilun\Application\Analytics
 */

declare(strict_types=1);

namespace Affilun\Application\Analytics;

use DateInterval;
use DateTimeImmutable;
use DateTimeZone;
use InvalidArgumentException;

/**
 * Immutable retention policy for click analytics tables.
 */
final class ClickRetentionPolicy {

	/**
	 * Default retention window in days.
	 */
	public const DEFAULT_RETENTION_DAYS = 180;

	/**
	 * Minimum retention window in days.
	 */
	public const MINIMUM_RETENTION_DAYS = 7;

	/**
	 * Configured retention window in days.
	 */
	private int $retentionDays;

	/**
	 * Construct the policy.
	 *
	 * @param int $retentionDays Retention window in days.
	 */
	public function __construct( int $retentionDays = self::DEFAULT_RETENTION_DAYS ) {
		if ( $retentionDays < self::MINIMUM_RETENTION_DAYS ) {
			throw new InvalidArgumentException( 'ClickRetentionPolicy retentionDays is too short.' );
		}
		$this->retentionDays = $retentionDays;
	}

	/**
	 * Default retention policy.
	 */
	public static function default(): self {
		return new self( self::DEFAULT_RETENTION_DAYS );
	}

	/**
	 * Retention window in days.
	 */
	public function retentionDays(): int {
		return $this->retentionDays;
	}

	/**
	 * Compute retention cutoff.
	 *
	 * @param DateTimeImmutable $now Current time.
	 */
	public function cutoffFrom( DateTimeImmutable $now ): DateTimeImmutable {
		return $now->setTimezone( new DateTimeZone( 'UTC' ) )
			->sub( new DateInterval( 'P' . $this->retentionDays . 'D' ) );
	}
}
