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

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 Orange Money (stub — à implémenter avec l'API Orange Money WebPay).
 *
 * <p>Sandbox : https://developer.orange.com/apis/om-webpay
 * Requis : client_id, client_secret, merchant_key par pays.
 *
 * <p>Retourne un mock tant que {@code orange.api.client-id} n'est pas configuré.
 */
@Slf4j
@ApplicationScoped
public class OrangeMoneyPaymentProvider implements PaymentProvider {

    public static final String CODE = "ORANGE_MONEY";

    @ConfigProperty(name = "orange.api.client-id")
    Optional<String> clientIdOpt;

    @ConfigProperty(name = "orange.api.base-url", defaultValue = "https://api.orange.com/orange-money-webpay/dev/v1")
    String baseUrl;

    String clientId;

    @jakarta.annotation.PostConstruct
    void init() {
        clientId = clientIdOpt.orElse("");
    }

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

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

    @Override
    public PaymentStatus getStatus(String externalId) throws PaymentException {
        log.warn("Orange Money 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 webhook Orange Money + vérifier signature
        throw new PaymentException(CODE, "Webhook Orange Money non encore implémenté", 501);
    }

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