<?php

namespace App\Sms\Provider;

use Psr\Log\LoggerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class RanginehProvider implements SmsProviderInterface
{
    private const BASE = 'https://rest.payamresan.com/api/v1';

    public function __construct(
        private readonly HttpClientInterface $httpClient,
        private readonly LoggerInterface     $logger,
        // Nullable: env `%env(default::RANGINEH_API_KEY)%` resolves to null when unset,
        // which would crash construction (TypeError) before the provider is ever used.
        private readonly ?string $apiKey = null,
        private readonly ?string $sender = null,
    ) {}

    public function getName(): string { return 'rangineh'; }

    public function send(string $mobile, string $message): bool
    {
        try {
            $resp = $this->httpClient->request('POST', self::BASE . '/send', [
                'json' => ['from' => $this->sender ?? '', 'to' => [$mobile], 'text' => $message],
                'headers' => ['ApiKey' => $this->apiKey ?? ''],
                'timeout' => 10,
            ]);
            return $resp->getStatusCode() === 200;
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('SMS send failed (rangineh): %s @ %s:%d', $e->getMessage(), $e->getFile(), $e->getLine()), ['exception' => $e, 'mobile' => $mobile]);
            return false;
        }
    }

    public function sendTemplate(string $mobile, string $templateCode, array $vars): bool
    {
        try {
            $resp = $this->httpClient->request('POST', self::BASE . '/send/verify', [
                'json' => [
                    'mobile'   => $mobile,
                    'template' => $templateCode,
                    'params'   => $vars,
                ],
                'headers' => ['ApiKey' => $this->apiKey],
                'timeout' => 10,
            ]);
            return $resp->getStatusCode() === 200;
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('SMS sendTemplate failed (rangineh): %s @ %s:%d', $e->getMessage(), $e->getFile(), $e->getLine()), ['exception' => $e, 'mobile' => $mobile, 'template' => $templateCode]);
            return false;
        }
    }
}
