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

declare(strict_types=1);

namespace BookiFlex\Extensions\Notification\Service;

use BookiFlex\Core\Model\Reservation\Reservation;
use BookiFlex\Extensions\Notification\Model\Recipient;
use BookiFlex\Extensions\Notification\Provider\NotificationContextProvider;
use Psr\Log\LoggerInterface;

defined('ABSPATH') || exit;

class NotificationSnapshotService
{
    public function __construct(
        private readonly NotificationContextProvider $contextProvider,
        private readonly ?LoggerInterface $logger = null,
    ) {
    }

    /**
     * Build a full snapshot for a specific stakeholder.
     * Returns null on failure (graceful degradation).
     *
     * @return array{context: array, template: string, subject: string}|null
     */
    public function build(Reservation $reservation, string $event, Recipient $stakeholder): ?array
    {
        try {
            $this->contextProvider->setReservation($reservation, $event);

            return [
                'context'  => $this->contextProvider->getContext(),
                'template' => $this->contextProvider->getTemplate($stakeholder),
                'subject'  => $this->contextProvider->getSubject($event, $stakeholder),
            ];
        } catch (\Throwable $e) {
            $this->logger?->warning('Failed to build notification snapshot', [
                'reservation_sid' => $reservation->getSid(),
                'event'           => $event,
                'stakeholder'     => $stakeholder->value,
                'error'           => $e->getMessage(),
            ]);

            return null;
        }
    }
}
