<?php

namespace App\Domains\Integration\Services;

use Carbon\Carbon;
use Exception;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class TelepagosIntegrationService extends BaseIntegrationService
{
    /**
     * TelepagosIntegrationService constructor.
     */
    public function __construct(string $integrationCode = 'telepagos')
    {
        // Force homologation code if not in production and using default
        if ($integrationCode === 'telepagos' && ! app()->environment('production')) {
            $integrationCode = 'telepagos_homo';
        }

        $this->integrationCode = $integrationCode;
    }

    /**
     * Get the headers for Telepagos integration.
     *
     * @throws Exception
     */
    public function getHeaders(): array
    {
        return [
            'Authorization' => 'Bearer '.$this->getToken(),
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
        ];
    }

    /**
     * Get a valid token, either from cache or by performing a login.
     *
     * @throws Exception
     */
    public function getToken(): string
    {
        if (! $this->clientIntegration || ! $this->clientContext) {
            throw new Exception('Client integration is not loaded. Call forTenant() or forClient() first.');
        }

        $cacheKey = "integration_token:{$this->clientContext->id}:{$this->integrationCode}";

        $token = Cache::get($cacheKey);

        if ($token) {
            return $token;
        }

        return $this->login();
    }

    /**
     * Authenticate with Telepagos and cache the returned token.
     *
     * @throws Exception
     */
    public function login(): string
    {
        $username = $this->getIntegrationSetting('username');
        $password = $this->getIntegrationSetting('password');

        if (empty($username) || empty($password)) {
            throw new Exception('Missing username or password in Telepagos integration settings.');
        }

        $url = $this->getUrl('/v2/auth/token');

        $response = Http::post($url, [
            'username' => $username,
            'password' => $password,
        ]);

        $data = $this->handleResponse($response, 'authentication');

        $token = $data['token'] ?? null;
        $expiresAtStr = $data['expires_at'] ?? null;

        if (! $token || ! $expiresAtStr) {
            throw new Exception('Telepagos authentication response is missing token or expires_at.');
        }

        $expiresAt = Carbon::parse($expiresAtStr);
        // Calculate TTL and subtract a buffer of 60 seconds
        $ttlSeconds = max(1, $expiresAt->diffInSeconds(now()) - 60);

        $cacheKey = "integration_token:{$this->clientContext->id}:{$this->integrationCode}";
        Cache::put($cacheKey, $token, $ttlSeconds);

        return $token;
    }

    /**
     * Send a request to Telepagos, handling 401 Unauthorized for token refresh.
     */
    protected function sendRequest(string $method, string $endpoint, array $data = []): Response
    {
        $response = $this->client()->$method($endpoint, $data);

        if ($response->status() === 401) {
            Log::channel('telepagos')->info('Telepagos request returned 401; refreshing token and retrying.', [
                'method' => strtoupper($method),
                'endpoint' => $endpoint,
                'client_id' => $this->clientContext?->id,
                'integration_code' => $this->integrationCode,
            ]);

            $this->clearToken();

            $response = $this->client()->$method($endpoint, $data);
        }

        return $response;
    }

    /**
     * Generate a QR code for cash-in.
     *
     * @throws Exception
     */
    public function generateQr(float $amount, string $concept, string $description): array
    {
        $payload = [
            'amount' => $amount,
            'concept' => $concept,
            'description' => $description,
        ];

        $response = $this->sendRequest('post', '/v2/payment/cashin/qr/generate', $payload);

        return $this->handleResponse($response, 'QR generation', $payload);
    }

    /**
     * Get the details of a cash-in payment.
     *
     * @param  int  $cashinId
     *
     * @throws Exception
     */
    public function getCashinDetails(string $cashinId): array
    {
        $response = $this->sendRequest('get', "/v2/payment/cashin/{$cashinId}");

        return $this->handleResponse($response, 'get cash-in details', [
            'cashin_id' => $cashinId,
        ]);
    }

    /**
     * Get the account info.
     *
     * @throws Exception
     */
    public function getAccountInfo(): array
    {
        $response = $this->sendRequest('get', '/v2/account/info');

        return $this->handleResponse($response, 'get account info');
    }

    /**
     * Handle the Telepagos API response, logging any failures and throwing Exceptions.
     *
     * @throws Exception
     */
    protected function handleResponse(Response $response, string $actionDescription, array $context = []): array
    {
        if ($response->failed() || $response->json('status') !== 'ok') {
            $errorMessage = $response->json('message') ?? $response->body();
            Log::channel('telepagos')->error("Telepagos {$actionDescription} failed: {$errorMessage}", array_merge([
                'response_status' => $response->status(),
                'response_body' => $this->sanitizeForLog($response->json() ?? $response->body()),
                'client_id' => $this->clientContext?->id,
                'integration_code' => $this->integrationCode,
            ], $context));

            throw new Exception("Telepagos {$actionDescription} failed: {$errorMessage}");
        }

        return $response->json() ?? [];
    }

    /**
     * Remove credentials and tokens before serializing provider responses.
     */
    protected function sanitizeForLog(mixed $value): mixed
    {
        if (! is_array($value)) {
            return $value;
        }

        $sensitiveKeys = ['authorization', 'password', 'token', 'access_token', 'refresh_token'];

        foreach ($value as $key => $item) {
            if (in_array(strtolower((string) $key), $sensitiveKeys, true)) {
                $value[$key] = '[REDACTED]';

                continue;
            }

            $value[$key] = $this->sanitizeForLog($item);
        }

        return $value;
    }

    /**
     * Clear the cached token.
     */
    public function clearToken(): void
    {
        if (! $this->clientContext) {
            return;
        }

        $cacheKey = "integration_token:{$this->clientContext->id}:{$this->integrationCode}";
        Cache::forget($cacheKey);
    }

    /**
     * Perform initial setup validation for Telepagos.
     *
     * @throws Exception
     */
    public function onSetup(): void
    {
        // Realiza un login de prueba para validar que las credenciales son correctas.
        $this->login();
    }
}
