<?php

namespace App\Http\Controllers;

use App\Services\WebhookService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class WebhookController extends Controller
{
    public function __construct(
        private readonly WebhookService $webhookService,
    ) {}

    public function pagarme(Request $request): JsonResponse
    {
        if (! $this->validPagarmeCredentials($request)) {
            return $this->errorResponse(message: __('http.unauthorized_token'), code: 401);
        }

        $this->webhookService->handlePagarme($request->all());

        return $this->successResponse(message: __('http.webhook_received'));
    }

    //

    private function validPagarmeCredentials(Request $request): bool
    {
        $configuredUser     = config('services.pagarme.webhook_user');
        $configuredPassword = config('services.pagarme.webhook_password');

        if (empty($configuredUser) || empty($configuredPassword)) {
            return false;
        }

        return is_string($configuredUser)
            && is_string($configuredPassword)
            && $this->validBasicAuthCredentials($request, $configuredUser, $configuredPassword);
    }

    private function validBasicAuthCredentials(Request $request, string $configuredUser, string $configuredPassword): bool
    {
        $receivedUser     = $request->getUser();
        $receivedPassword = $request->getPassword();

        return is_string($receivedUser)
            && is_string($receivedPassword)
            && hash_equals($configuredUser, $receivedUser)
            && hash_equals($configuredPassword, $receivedPassword);
    }
}
