import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Objects;

final class HttpLoginAlertDelivery {
    private final HttpClient client;
    private final URI endpoint;

    HttpLoginAlertDelivery(HttpClient client, URI endpoint) {
        this.client = Objects.requireNonNull(client);
        this.endpoint = Objects.requireNonNull(endpoint);
        if (!"https".equalsIgnoreCase(endpoint.getScheme())
                || endpoint.getHost() == null) {
            throw new IllegalArgumentException("Configured HTTPS endpoint required");
        }
    }

    void deliver(LoginDemo.LoginAlert alert)
            throws IOException, InterruptedException {
        String form = "messageId=" + encode(alert.eventId())
                + "&recipient=" + encode(alert.recipient())
                + "&body=" + encode(alert.message());
        HttpRequest request = HttpRequest.newBuilder(endpoint)
                .timeout(Duration.ofSeconds(5))
                .header("Content-Type", "application/x-www-form-urlencoded")
                .header("Idempotency-Key", alert.eventId())
                .POST(HttpRequest.BodyPublishers.ofString(form))
                .build();
        int status = client.send(request,
                HttpResponse.BodyHandlers.discarding()).statusCode();
        if (status >= 200 && status < 300) {
            return; // Accepted by this gateway, not necessarily delivered.
        }
        if (status == 429 || status >= 500) {
            throw new IOException("Retryable gateway status: " + status);
        }
        throw new PermanentRejection(status);
    }

    private static String encode(String value) {
        return URLEncoder.encode(value, StandardCharsets.UTF_8);
    }

    static final class PermanentRejection extends IOException {
        PermanentRejection(int status) {
            super("Gateway rejected alert: " + status);
        }
    }
}
