<?php
declare(strict_types=1);

namespace App\Modules\Cron;

use App\Modules\Settings\AllegroIntegrationRepository;
use App\Modules\Settings\AllegroOAuthClient;
use DateInterval;
use DateTimeImmutable;
use RuntimeException;

final class AllegroTokenRefreshHandler
{
    public function __construct(
        private readonly AllegroIntegrationRepository $repository,
        private readonly AllegroOAuthClient $oauthClient
    ) {
    }

    /**
     * @param array<string, mixed> $payload
     * @return array<string, mixed>
     */
    public function handle(array $payload): array
    {
        $credentials = $this->repository->getRefreshTokenCredentials();
        if ($credentials === null) {
            throw new RuntimeException('Brak kompletnych danych Allegro OAuth do odswiezenia tokenu.');
        }

        $token = $this->oauthClient->refreshAccessToken(
            (string) ($credentials['environment'] ?? 'sandbox'),
            (string) ($credentials['client_id'] ?? ''),
            (string) ($credentials['client_secret'] ?? ''),
            (string) ($credentials['refresh_token'] ?? '')
        );

        $expiresAt = null;
        $expiresIn = max(0, (int) ($token['expires_in'] ?? 0));
        if ($expiresIn > 0) {
            $expiresAt = (new DateTimeImmutable('now'))
                ->add(new DateInterval('PT' . $expiresIn . 'S'))
                ->format('Y-m-d H:i:s');
        }

        $refreshToken = trim((string) ($token['refresh_token'] ?? ''));
        if ($refreshToken === '') {
            $refreshToken = (string) ($credentials['refresh_token'] ?? '');
        }

        $this->repository->saveTokens(
            (string) ($token['access_token'] ?? ''),
            $refreshToken,
            (string) ($token['token_type'] ?? ''),
            (string) ($token['scope'] ?? ''),
            $expiresAt
        );

        return [
            'ok' => true,
            'expires_at' => $expiresAt,
        ];
    }
}
