<?php

declare(strict_types=1);

namespace App\Application\Webhook\Controller;

use App\Framework\Attributes\Route;
use App\Framework\Core\Events\EventDispatcher;
use App\Framework\EventBus\Attributes\OnEvent;
use App\Framework\Http\HttpRequest;
use App\Framework\Http\HttpResponse;
use App\Framework\Http\Method;
use App\Framework\Http\Responses\JsonResponse;
use App\Framework\Webhook\Attributes\WebhookEndpoint;
use App\Framework\Webhook\Events\WebhookReceived;
use App\Framework\Webhook\WebhookService;

/**
 * Example webhook controller for legal content updates (Impressum/Privacy)
 * Demonstrates both incoming webhook processing and event handling
 */
final readonly class LegalWebhookController
{
    public function __construct(
        private WebhookService $webhookService,
        private EventDispatcher $eventDispatcher
    ) {
    }

    /**
     * Receive legal content updates via webhook
     */
    #[Route(path: '/api/webhooks/legal', method: Method::POST)]
    #[WebhookEndpoint(
        provider: 'legal-service',
        events: ['legal.content.updated', 'legal.content.created'],
        async: true
    )]
    public function receiveLegalUpdate(HttpRequest $request): Response
    {
        // WebhookMiddleware handles automatic processing
        // This method is called after successful signature verification

        return new JsonResponse([
            'status' => 'received',
            'message' => 'Legal content webhook processed successfully',
        ]);
    }

    /**
     * Handle legal content webhook events
     */
    #[OnEvent]
    public function handleLegalContentUpdate(WebhookReceived $event): void
    {
        if (! $event->isFromProvider('legal-service')) {
            return;
        }

        match ($event->eventType) {
            'legal.content.updated' => $this->updateLegalContent($event),
            'legal.content.created' => $this->createLegalContent($event),
            default => null
        };
    }

    /**
     * Example: Send legal content update to external service
     */
    #[Route(path: '/api/admin/legal/notify', method: Method::POST)]
    public function notifyLegalUpdate(HttpRequest $request): HttpResponse
    {
        $data = $request->parsedBody->toArray();

        // Send webhook to external service
        $jobId = $this->webhookService->sendLegalUpdate(
            url: 'https://external-service.com/webhooks/legal',
            legalData: $data,
            secret: 'webhook-secret', // Should come from environment
            async: true
        );

        return new JsonResponse([
            'status' => 'scheduled',
            'job_id' => $jobId,
            'message' => 'Legal update webhook scheduled for delivery',
        ]);
    }

    private function updateLegalContent(WebhookReceived $event): void
    {
        $content = $event->getData();

        // Update impressum/privacy content in database
        // Example logic - would use proper domain services

        // Log the update
        // $context = LogContext::withData([
        //     'content_type' => $content['type'] ?? 'unknown',
        //     'language' => $content['language'] ?? 'de',
        //     'webhook_id' => $event->webhookId
        // ])->addTags('webhook', 'legal');
        // $this->logger->info('Legal content updated via webhook', $context);
    }

    private function createLegalContent(WebhookReceived $event): void
    {
        $content = $event->getData();

        // Create new legal content in database
        // Example logic - would use proper domain services
    }
}
