package dev.lions.unionflow.server.payment.mtnmomo;

import dev.lions.unionflow.server.api.payment.*;
import jakarta.enterprise.context.ApplicationScoped;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.config.inject.ConfigProperty;

import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

/**
 * Provider MTN MoMo (stub — à implémenter avec l'API MTN Mobile Money).
 *
 * <p>Sandbox : https://sandbox.momodeveloper.mtn.com
 * Requis : subscription-key, api-user, api-key (via provisioning sandbox).
 */
@Slf4j
@ApplicationScoped
public class MtnMomoPaymentProvider implements PaymentProvider {

    public static final String CODE = "MTN_MOMO";

    @ConfigProperty(name = "mtnmomo.collection.subscription-key")
    Optional<String> subscriptionKeyOpt;

    @ConfigProperty(name = "mtnmomo.api.base-url", defaultValue = "https://sandbox.momodeveloper.mtn.com")
    String baseUrl;

    String subscriptionKey;

    @jakarta.annotation.PostConstruct
    void init() {
        subscriptionKey = subscriptionKeyOpt.orElse("");
    }

    @Override
    public String getProviderCode() {
        return CODE;
    }

    @Override
    public CheckoutSession initiateCheckout(CheckoutRequest request) throws PaymentException {
        if (subscriptionKey == null || subscriptionKey.isBlank()) {
            log.warn("MTN MoMo non configuré — mode mock actif pour ref={}", request.reference());
            String mockId = "MTN-MOCK-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
            return new CheckoutSession(mockId, "https://mock.mtn.ci/pay/" + mockId,
                    Instant.now().plusSeconds(600), Map.of("mock", "true", "provider", CODE));
        }
        // TODO P1.3 Phase 3 : implémenter MTN Collection API (requestToPay)
        throw new PaymentException(CODE, "MTN MoMo non encore implémenté en production", 501);
    }

    @Override
    public PaymentStatus getStatus(String externalId) throws PaymentException {
        log.warn("MTN MoMo getStatus mock pour externalId={}", externalId);
        return PaymentStatus.PROCESSING;
    }

    @Override
    public PaymentEvent processWebhook(String rawBody, Map<String, String> headers) throws PaymentException {
        // TODO P1.3 Phase 3 : parser callback MTN MoMo
        throw new PaymentException(CODE, "Webhook MTN MoMo non encore implémenté", 501);
    }

    @Override
    public boolean isAvailable() {
        return subscriptionKey != null && !subscriptionKey.isBlank();
    }
}
