package com.saas.voip.service;

import com.saas.tenant.entity.InboundCallRequest;
import com.saas.tenant.repository.InboundCallRequestRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

@Service
@RequiredArgsConstructor
@Slf4j
public class ZiwoSmsService {

    private final ZiwoApiService ziwoApiService;
    private final InboundCallRequestRepository inboundCallRequestRepository;

    private static final DateTimeFormatter FRENCH_DATE_FORMATTER = 
        DateTimeFormatter.ofPattern("EEEE d MMMM yyyy 'à' HH'h'mm", Locale.FRENCH);

    public void sendAppointmentConfirmation(
        Long requestId,
        String fromNumber,
        String toNumber,
        String patientName,
        String doctorName,
        LocalDateTime appointmentDateTime
    ) {
        try {
            String message = buildConfirmationMessage(patientName, doctorName, appointmentDateTime);

            log.info("Sending Ziwo SMS confirmation to: {} from: {}", toNumber, fromNumber);

            Map<String, Object> result = ziwoApiService.sendSms(fromNumber, toNumber, message);

            if (result != null) {
                String smsSid = result.get("message_id") != null ? result.get("message_id").toString() : null;
                String smsStatus = result.get("status") != null ? result.get("status").toString() : "sent";

                Optional<InboundCallRequest> requestOpt = inboundCallRequestRepository.findById(requestId);
                if (requestOpt.isPresent()) {
                    InboundCallRequest request = requestOpt.get();
                    request.setSmsSent(true);
                    request.setSmsSid(smsSid);
                    request.setSmsStatus(smsStatus);
                    inboundCallRequestRepository.save(request);
                    log.info("Updated InboundCallRequest with Ziwo SMS details: smsSid={}", smsSid);
                }
            } else {
                log.error("Failed to send Ziwo SMS confirmation");
            }

        } catch (Exception e) {
            log.error("Error sending Ziwo SMS confirmation", e);
        }
    }

    public void sendCustomSms(String fromNumber, String toNumber, String message) {
        try {
            log.info("Sending custom Ziwo SMS to: {} from: {}", toNumber, fromNumber);

            Map<String, Object> result = ziwoApiService.sendSms(fromNumber, toNumber, message);

            if (result != null) {
                log.info("Custom Ziwo SMS sent successfully");
            } else {
                log.error("Failed to send custom Ziwo SMS");
            }

        } catch (Exception e) {
            log.error("Error sending custom Ziwo SMS", e);
        }
    }

    private String buildConfirmationMessage(
        String patientName,
        String doctorName,
        LocalDateTime appointmentDateTime
    ) {
        String formattedDateTime = appointmentDateTime != null 
            ? appointmentDateTime.format(FRENCH_DATE_FORMATTER)
            : "à confirmer";

        return String.format(
            "Bonjour %s,\n\nVotre rendez-vous avec %s est confirmé pour le %s.\n\nÀ bientôt !",
            patientName != null ? patientName : "cher(e) patient(e)",
            doctorName != null ? doctorName : "le médecin",
            formattedDateTime
        );
    }
}
