<?php

declare(strict_types=1);

namespace App\Framework\Notification\Channels\Telegram\Webhook;

use App\Framework\Attributes\Route;
use App\Framework\Http\HttpRequest;
use App\Framework\Http\Method;
use App\Framework\Router\Result\JsonResult;
use App\Framework\Webhook\Attributes\WebhookEndpoint;
use App\Framework\Webhook\Processing\WebhookRequestHandler;

/**
 * Telegram Webhook Controller
 *
 * Receives webhook updates from Telegram Bot API
 * Uses framework's WebhookRequestHandler for automatic processing
 */
final readonly class TelegramWebhookController
{
    public function __construct(
        private WebhookRequestHandler $webhookHandler
    ) {
    }

    /**
     * Handle incoming Telegram webhook updates
     *
     * Telegram sends updates for:
     * - New messages
     * - Callback queries (inline keyboard button clicks)
     * - Edited messages
     * - Channel posts
     * - And more...
     *
     * @see https://core.telegram.org/bots/api#update
     */
    #[Route(path: '/webhooks/telegram', method: Method::POST)]
    #[WebhookEndpoint(
        provider: 'telegram',
        events: ['message', 'callback_query', 'edited_message'],
        async: false, // Process synchronously for immediate callback responses
        timeout: 10,
        idempotent: true
    )]
    public function handleWebhook(HttpRequest $request): JsonResult
    {
        // Get secret token from environment
        $secretToken = $_ENV['TELEGRAM_WEBHOOK_SECRET'] ?? '';

        if (empty($secretToken)) {
            return new JsonResult([
                'status' => 'error',
                'message' => 'Webhook secret not configured',
            ], 500);
        }

        // Let framework's WebhookRequestHandler do the heavy lifting:
        // - Signature verification
        // - Idempotency checking
        // - Event dispatching
        // - Error handling
        return $this->webhookHandler->handle(
            request: $request,
            provider: TelegramWebhookProvider::create(),
            secret: $secretToken,
            allowedEvents: ['message', 'callback_query', 'edited_message']
        );
    }
}
