package pl.polskalokalnie.send;

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import org.springframework.stereotype.Component;
import pl.polskalokalnie.mailconfig.SmsGatewayConfig;

/**
 * Wysylka pojedynczego SMS przez bramke SoftSPM ({@code send_sms_api.php}). Zadanie HTTP POST
 * (form-urlencoded) z kluczem API, polem creator, numerem i trescia; timeout z konfiguracji.
 *
 * UWAGA: dokladne nazwy parametrow bramki (apiKey/creator/to/message) nalezy potwierdzic z
 * dokumentacja SoftSPM - sa wyodrebnione ponizej, by latwo je dopasowac.
 */
@Component
public class SmsSender {

    private static final String PARAM_API_KEY = "apiKey";
    private static final String PARAM_CREATOR = "creator";
    private static final String PARAM_TO = "to";
    private static final String PARAM_MESSAGE = "message";

    public SendResult send(SmsGatewayConfig config, String phone, String message) {
        if (config == null || config.getEndpointUrl() == null || config.getEndpointUrl().isBlank()
                || config.getApiKey() == null || config.getApiKey().isBlank()) {
            return SendResult.failure("Konfiguracja bramki SMS jest niekompletna");
        }
        try {
            int timeout = config.getTimeoutSeconds() != null && config.getTimeoutSeconds() > 0
                    ? config.getTimeoutSeconds() : 10;
            String form = PARAM_API_KEY + "=" + enc(config.getApiKey())
                    + "&" + PARAM_CREATOR + "=" + enc(config.getCreator())
                    + "&" + PARAM_TO + "=" + enc(phone)
                    + "&" + PARAM_MESSAGE + "=" + enc(message);

            HttpClient client = HttpClient.newBuilder()
                    .connectTimeout(Duration.ofSeconds(timeout))
                    .build();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(config.getEndpointUrl()))
                    .timeout(Duration.ofSeconds(timeout))
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .POST(HttpRequest.BodyPublishers.ofString(form, StandardCharsets.UTF_8))
                    .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            String body = response.body() == null ? "" : response.body().trim();
            if (response.statusCode() >= 200 && response.statusCode() < 300) {
                return SendResult.ok(shorten(body));
            }
            return SendResult.failure("Bramka SMS zwróciła status " + response.statusCode()
                    + (body.isEmpty() ? "" : ": " + shorten(body)));
        } catch (Exception ex) {
            return SendResult.failure(shorten(ex.getMessage()));
        }
    }

    private static String enc(String value) {
        return URLEncoder.encode(value == null ? "" : value, StandardCharsets.UTF_8);
    }

    private static String shorten(String value) {
        if (value == null) {
            return "";
        }
        return value.length() > 200 ? value.substring(0, 200) : value;
    }
}
