package com.saas.voip.service;

import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import jakarta.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

@Service
@Slf4j
public class TwilioSmsService {

    @Value("${twilio.account.sid}")
    private String accountSid;

    @Value("${twilio.auth.token}")
    private String authToken;

    @Value("${twilio.phone.number}")
    private String twilioPhoneNumber;

    @PostConstruct
    public void init() {
        Twilio.init(accountSid, authToken);
        log.info("Twilio SMS Service initialized with number: {}", twilioPhoneNumber);
    }

    public String sendAppointmentConfirmationSms(
            String toPhoneNumber,
            String patientName,
            String doctorName,
            LocalDateTime appointmentDateTime,
            String statusCallbackUrl) {
        
        try {
            // Null check for appointmentDateTime to prevent NPE
            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
            );

            // Create message with status callback
            var messageCreator = Message.creator(
                    new PhoneNumber(toPhoneNumber),
                    new PhoneNumber(twilioPhoneNumber),
                    messageBody
            );
            
            // Add status callback if URL is provided
            if (statusCallbackUrl != null && !statusCallbackUrl.isEmpty()) {
                try {
                    messageCreator.setStatusCallback(java.net.URI.create(statusCallbackUrl));
                    log.debug("📍 SMS Status Callback URL set: {}", statusCallbackUrl);
                } catch (Exception e) {
                    log.warn("Failed to set status callback URL: {}", statusCallbackUrl);
                }
            }
            
            Message message = messageCreator.create();

            log.info("📨 SMS envoyé avec succès ! SID: {} | Statut: {} | Destinataire: {}", 
                    message.getSid(), message.getStatus(), toPhoneNumber);
            
            return message.getSid();

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

    public boolean sendCustomSms(String toPhoneNumber, String messageBody) {
        try {
            Message message = Message.creator(
                    new PhoneNumber(toPhoneNumber),
                    new PhoneNumber(twilioPhoneNumber),
                    messageBody
            ).create();

            log.info("📨 SMS personnalisé envoyé ! SID: {} | Destinataire: {}", 
                    message.getSid(), toPhoneNumber);
            
            return true;

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