<?php
/**
 * BookiFlex Core
 *
 * @package    BookiFlex
 * @subpackage Core
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Core\Service\Reservation;

use BookiFlex\Core\Contract\Payment\PaymentAllocationProviderInterface;
use BookiFlex\Core\Exception\RuntimeException;
use BookiFlex\Core\Repository\PenaltyRepository;
use BookiFlex\Core\Repository\ReservationRepository;
use Cycle\ORM\EntityManagerInterface;

defined( 'ABSPATH' ) || exit;

class ReservationService
{
    public function __construct(
        private readonly ReservationRepository $reservationRepository,
        private readonly PenaltyRepository $penaltyRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly ?PaymentAllocationProviderInterface $paymentAllocationProvider = null
    ) {
    }

    public function show($reservationId): array
    {
        $reservation        = $this->reservationRepository->findByPK($reservationId);
        $reservations       = ($group = $reservation->getGroup()) ? $group->getReservations() : [$reservation];
        $paymentAllocations = ($this->paymentAllocationProvider)
            ? $this->paymentAllocationProvider->getPaymentAllocations($reservations)
            : [];

        return [
            'reservation' => $reservation, 'paymentAllocations' => $paymentAllocations
        ];
    }

    /**
     * @throws RuntimeException
     */
    public function resolvePenalty(int $penaltyId, ?string $comment = null): void
    {
        $penalty = $this->penaltyRepository->findById($penaltyId);
        if (!$penalty) {
            throw new RuntimeException('Penalty not found');
        }

        $penalty->markAsResolved($comment);
        $this->save($penalty);
    }

    private function save(object $entity): void
    {
        $this->entityManager->persist($entity);
        $this->entityManager->run();
    }
}
