package com.saas.voip.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * Service for sending SMS via Telnyx API
 * Alternative to Twilio SMS
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class TelnyxSmsService {

    private final RestTemplate restTemplate = new RestTemplate();

    @Value("${telnyx.api.key:}")
    private String telnyxApiKey;

    @Value("${telnyx.messaging.profile.id:}")
    private String messagingProfileId;

    private static final String TELNYX_SMS_API = "https://api.telnyx.com/v2/messages";

    /**
     * Send appointment confirmation SMS via Telnyx
     */
    public String sendAppointmentConfirmationSms(
            String fromPhoneNumber,
            String toPhoneNumber,
            String patientName,
            String doctorName,
            LocalDateTime appointmentDateTime,
            String statusCallbackUrl) {
        
        try {
            if (appointmentDateTime == null) {
                log.warn("⚠️ Appointment date/time is null, cannot send SMS to {}", toPhoneNumber);
                return null;
            }
            
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE dd MMMM yyyy 'à' HH'h'mm", Locale.FRENCH);
            String formattedDateTime = appointmentDateTime.format(formatter);
            
            String messageBody = String.format(
                "✅ Confirmation de rendez-vous - Clinique La Rive Bleue\n\n" +
                "Bonjour %s,\n\n" +
                "Votre rendez-vous avec %s est confirmé pour le %s.\n\n" +
                "Merci de votre confiance.\n\n" +
                "Clinique La Rive Bleue",
                patientName,
                doctorName,
                formattedDateTime
            );

            return sendSms(fromPhoneNumber, toPhoneNumber, messageBody, statusCallbackUrl);

        } catch (Exception e) {
            log.error("❌ Erreur lors de l'envoi du SMS Telnyx à {}: {}", toPhoneNumber, e.getMessage(), e);
            return null;
        }
    }

    /**
     * Send custom SMS via Telnyx
     */
    public boolean sendCustomSms(String fromPhoneNumber, String toPhoneNumber, String messageBody) {
        try {
            String messageSid = sendSms(fromPhoneNumber, toPhoneNumber, messageBody, null);
            return messageSid != null;
        } catch (Exception e) {
            log.error("❌ Erreur lors de l'envoi du SMS personnalisé Telnyx: {}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * Core method to send SMS via Telnyx API
     */
    private String sendSms(String fromPhoneNumber, String toPhoneNumber, String text, String webhookUrl) {
        try {
            Map<String, Object> payload = new HashMap<>();
            payload.put("from", fromPhoneNumber);
            payload.put("to", toPhoneNumber);
            payload.put("text", text);
            
            if (messagingProfileId != null && !messagingProfileId.isEmpty()) {
                payload.put("messaging_profile_id", messagingProfileId);
            }
            
            if (webhookUrl != null && !webhookUrl.isEmpty()) {
                payload.put("webhook_url", webhookUrl);
            }

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(telnyxApiKey);

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(payload, headers);

            ResponseEntity<Map> response = restTemplate.exchange(TELNYX_SMS_API, HttpMethod.POST, request, Map.class);

            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                Map<String, Object> data = (Map<String, Object>) response.getBody().get("data");
                String messageId = data != null ? (String) data.get("id") : null;
                
                log.info("📨 SMS Telnyx envoyé avec succès ! ID: {} | Destinataire: {}", messageId, toPhoneNumber);
                return messageId;
            } else {
                log.error("❌ Échec envoi SMS Telnyx. Status: {}", response.getStatusCode());
                return null;
            }

        } catch (Exception e) {
            log.error("❌ Erreur lors de l'envoi du SMS Telnyx: {}", e.getMessage(), e);
            return null;
        }
    }
}
