<?php

namespace Velis\MaintenanceAlert;

use DateTimeImmutable;

/**
 * @author Szymon Janaczek <szymon.janaczek@velistech.com>
 */
final class MaintenanceAlertFormatter implements MaintenanceAlertFormatterInterface
{
    public function __construct(
        private readonly string $alertTemplate,
        private readonly string $fromTimePlaceholder = 'XXX',
        private readonly string $toTimePlaceholder = 'YYY',
    ) {
    }

    public function format(DateTimeImmutable $startDate, DateTimeImmutable $stopDate): string
    {
        $formattedStart = $this->formatDate($startDate);
        $formattedStop = $this->formatStop($startDate, $stopDate);

        return strtr($this->alertTemplate, [
            $this->fromTimePlaceholder => $formattedStart,
            $this->toTimePlaceholder => $formattedStop,
        ]);
    }

    private function formatDate(DateTimeImmutable $date): string
    {
        return $date->format('Y-m-d H:i');
    }

    private function formatStop(DateTimeImmutable $startDate, DateTimeImmutable $stopDate): string
    {
        return $startDate->format('Y-m-d') === $stopDate->format('Y-m-d')
            ? $stopDate->format('H:i')
            : $this->formatDate($stopDate);
    }
}
