package com.saas.voip.extractor;

import com.saas.tenant.entity.InboundCallData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

@Component
@Slf4j
public class TelnyxCallDataExtractor {

    private static final DateTimeFormatter ISO_FORMATTER = DateTimeFormatter.ISO_DATE_TIME;

    public InboundCallData extractFromTelnyxRequest(Map<String, Object> payload) {
        try {
            Map<String, Object> eventData = (Map<String, Object>) payload.get("data");
            Map<String, Object> callPayload = (Map<String, Object>) eventData.get("payload");
            
            InboundCallData callData = new InboundCallData();
            
            // Basic call info
            callData.setCallSid(getString(callPayload, "call_session_id"));
            callData.setProvider("TELNYX");
            callData.setFromNumber(getString(callPayload, "from"));
            callData.setToNumber(getString(callPayload, "to"));
            callData.setCallStatus(getString(callPayload, "state", "initiated"));
            callData.setDirection(getString(callPayload, "direction", "inbound"));
            
            // Call identifiers
            callData.setCallToken(getString(callPayload, "call_control_id"));
            
            // Caller info
            callData.setFromCity(getString(callPayload, "from_number_object.city"));
            callData.setFromState(getString(callPayload, "from_number_object.state"));
            callData.setFromCountry(getString(callPayload, "from_number_object.country"));
            
            // Called info  
            callData.setToCity(getString(callPayload, "to_number_object.city"));
            callData.setToState(getString(callPayload, "to_number_object.state"));
            callData.setToCountry(getString(callPayload, "to_number_object.country"));
            
            // Timestamps
            String startTimeStr = getString(callPayload, "start_time");
            if (startTimeStr != null && !startTimeStr.isEmpty()) {
                try {
                    callData.setStartTime(LocalDateTime.parse(startTimeStr, ISO_FORMATTER));
                } catch (Exception e) {
                    log.warn("Failed to parse start_time: {}", startTimeStr);
                }
            }
            
            log.debug("📋 Extracted Telnyx call data - CallSid: {}, From: {}, To: {}", 
                    callData.getCallSid(), callData.getFromNumber(), callData.getToNumber());
            
            return callData;
            
        } catch (Exception e) {
            log.error("Error extracting Telnyx call data", e);
            throw new RuntimeException("Failed to extract Telnyx call data", e);
        }
    }
    
    private String getString(Map<String, Object> map, String key) {
        return getString(map, key, null);
    }
    
    private String getString(Map<String, Object> map, String key, String defaultValue) {
        if (map == null) return defaultValue;
        
        // Handle nested keys like "from_number_object.city"
        if (key.contains(".")) {
            String[] parts = key.split("\\.", 2);
            Object nested = map.get(parts[0]);
            if (nested instanceof Map) {
                return getString((Map<String, Object>) nested, parts[1], defaultValue);
            }
            return defaultValue;
        }
        
        Object value = map.get(key);
        return value != null ? value.toString() : defaultValue;
    }
}
