<?php

namespace App\Http\Controllers;

use App\Services\AiChat\MetaChatChannelService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class MetaChatWebhookController extends Controller
{
    public function __construct(private readonly MetaChatChannelService $metaChatChannelService)
    {
    }

    public function verify(Request $request, string $channel)
    {
        $challenge = $this->metaChatChannelService->handleVerification(
            $channel,
            $request->query('hub_mode'),
            $request->query('hub_verify_token'),
            $request->query('hub_challenge')
        );

        if ($challenge === null) {
            return response('Invalid webhook verification request.', 403);
        }

        return response($challenge, 200);
    }

    public function receive(Request $request, string $channel): JsonResponse
    {
        try {
            $processed = $this->metaChatChannelService->handleWebhook($channel, $request->all());

            return response()->json([
                'message' => 'Webhook processed successfully.',
                'processed' => $processed,
            ]);
        } catch (\Throwable $throwable) {
            Log::error('Meta chat webhook processing failed.', [
                'channel' => $channel,
                'message' => $throwable->getMessage(),
            ]);

            return response()->json([
                'message' => 'Webhook received.',
                'processed' => 0,
            ]);
        }
    }
}
