<?php

declare(strict_types=1);

namespace App\Service\Notification;

use App\Entity\EmployeeContractPeriod;
use App\Enum\ContractNature;
use DateTimeImmutable;

final readonly class ContractEndNotificationPlanner
{
    public function __construct(
        private WorkingDayCalculator $calculator,
    ) {}

    /**
     * @param EmployeeContractPeriod[] $latestPeriods
     *
     * @return ContractEndNotice[]
     */
    public function plan(array $latestPeriods, DateTimeImmutable $today): array
    {
        $today = $today->setTime(0, 0, 0);
        if (!$this->calculator->isWorkingDay($today)) {
            return [];
        }

        $upperBound = $this->calculator->nextWorkingDay($today);

        $notices = [];
        foreach ($latestPeriods as $period) {
            $endDate = $period->getEndDate();
            if (null === $endDate) {
                continue;
            }

            $endDate = $endDate->setTime(0, 0, 0);
            if ($endDate <= $today || $endDate > $upperBound) {
                continue;
            }

            $employee = $period->getEmployee();
            if (null === $employee) {
                continue;
            }

            $message = sprintf(
                'Fin de %s de %s %s le %s',
                $this->natureLabel($period->getContractNatureEnum()),
                $employee->getFirstName(),
                $employee->getLastName(),
                $endDate->format('d/m/Y'),
            );

            $notices[] = new ContractEndNotice($employee->getId(), $message);
        }

        return $notices;
    }

    private function natureLabel(ContractNature $nature): string
    {
        return match ($nature) {
            ContractNature::CDI     => 'CDI',
            ContractNature::CDD     => 'CDD',
            ContractNature::INTERIM => 'Intérim',
        };
    }
}
