<?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\Api\Controller;

use BookiFlex\Core\Api\Controller\AbstractController;
use BookiFlex\Core\Contract\RoleCapabilitiesInterface;
use BookiFlex\Extensions\Notification\Api\Request\GetReservationNotificationsRequest;
use BookiFlex\Extensions\Notification\Api\Transformer\NotificationTransformer;
use BookiFlex\Extensions\Notification\Repository\NotificationRepository;
use Throwable;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;

defined( 'ABSPATH' ) || exit;

class NotificationController extends AbstractController
{
    public const API_ENDPOINT_NAME = 'notifications';

    public function __construct(
        private readonly NotificationRepository $notificationRepository,
        string $namespace = 'bflex/v1'
    ) {
        parent::__construct($namespace);
    }

    public function registerRoutes(): void
    {
        // GET /notifications/reservation/{reservationId} — list client notifications
        register_rest_route($this->namespace, '/' . self::API_ENDPOINT_NAME . '/reservation/(?P<reservationId>\d+)', [
            [
                'methods'             => 'GET',
                'callback'            => [$this, 'getReservationNotifications'],
                'permission_callback' => [$this, 'hasAccess'],
                'args'                => GetReservationNotificationsRequest::getValidationRules(),
            ],
        ]);
    }

    /**
     * GET /notifications/reservation/{reservationId}
     */
    public function getReservationNotifications(WP_REST_Request $request): WP_REST_Response|WP_Error
    {
        try {
            $req = GetReservationNotificationsRequest::fromWpRestRequest($request);
            $notifications = $this->notificationRepository->findClientByReservationId($req->getReservationId());

            $transformer = new NotificationTransformer();

            return $this->success([
                'status' => 'success',
                'result' => $transformer->transformCollection($notifications),
            ]);
        } catch (Throwable $e) {
            return $this->handleError(
                $e,
                'notifications_load_failed',
                __('Failed to load notifications.', 'bookiflex')
            );
        }
    }

    public function hasAccess(): bool|WP_Error
    {
        if (!current_user_can(RoleCapabilitiesInterface::MANAGE_RESERVATIONS)) {
            return $this->error(
                'bookiflex_forbidden',
                __('You are not allowed to manage reservations.', 'bookiflex'),
                401
            );
        }

        return true;
    }
}