package com.saas.voip.service;

import com.saas.shared.core.TenantContext;
import com.saas.tenant.entity.RetellCall;
import com.saas.tenant.entity.RetellCallCostRecord;
import com.saas.tenant.repository.RetellCallRepository;
import com.saas.tenant.repository.RetellCallCostRecordRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * Retell Webhook Service
 * 
 * Phase 4.2 - Process Retell AI webhook events
 * Pure JPA, multi-tenant routing via TenantContext
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class RetellWebhookService {
    
    private final RetellCallRepository retellCallRepository;
    private final RetellCallCostRecordRepository retellCallCostRepository;
    
    private static final BigDecimal COST_PER_MINUTE = new BigDecimal("0.20"); // $0.20/min
    
    /**
     * Process call_started event
     */
    @Transactional
    public void processCallStarted(Map<String, Object> payload) {
        String callId = (String) payload.get("call_id");
        String agentId = (String) payload.get("agent_id");
        String tenantId = (String) payload.get("metadata.tenant_id"); // Assuming metadata
        
        log.info("📞 Retell call started - ID: {}", callId);
        
        if (tenantId == null) {
            log.warn("⚠️ No tenant_id in call_started webhook, skipping");
            return;
        }
        
        // Route to tenant DB
        TenantContext.setTenantId(tenantId);
        
        try {
            RetellCall call = RetellCall.builder()
                    .retellCallId(callId)
                    .status("IN_PROGRESS")
                    .startTime(LocalDateTime.now())
                    .build();
            
            retellCallRepository.save(call);
            log.info("✅ Retell call saved to tenant DB");
            
        } finally {
            TenantContext.clear();
        }
    }
    
    /**
     * Process call_ended event (transcript + cost tracking)
     */
    @Transactional
    public void processCallEnded(Map<String, Object> payload) {
        String callId = (String) payload.get("call_id");
        Integer durationSeconds = (Integer) payload.get("duration_seconds");
        String transcript = payload.get("transcript").toString();
        String tenantId = (String) payload.get("metadata.tenant_id");
        
        log.info("📝 Retell call ended - ID: {}, Duration: {}s", callId, durationSeconds);
        
        if (tenantId == null) {
            log.warn("⚠️ No tenant_id in call_ended webhook, skipping");
            return;
        }
        
        TenantContext.setTenantId(tenantId);
        
        try {
            // Update call record
            RetellCall call = retellCallRepository.findByRetellCallId(callId)
                    .orElseThrow(() -> new RuntimeException("Retell call not found: " + callId));
            
            call.setStatus("ENDED");
            call.setEndTime(LocalDateTime.now());
            call.setDurationSeconds(durationSeconds);
            call.setTranscript(transcript);
            
            retellCallRepository.save(call);
            
            // Calculate cost ($0.20/min)
            BigDecimal durationMinutes = new BigDecimal(durationSeconds).divide(new BigDecimal("60"), 2, BigDecimal.ROUND_HALF_UP);
            BigDecimal totalCost = durationMinutes.multiply(COST_PER_MINUTE);
            
            // Save cost record
            RetellCallCostRecord costRecord = RetellCallCostRecord.builder()
                    .retellCallId(callId)
                    .callStartTime(call.getStartTime())
                    .durationMinutes(durationMinutes)
                    .costPerMinute(COST_PER_MINUTE)
                    .totalCost(totalCost)
                    .currency("USD")
                    .build();
            
            retellCallCostRepository.save(costRecord);
            
            log.info("✅ Retell call + cost saved - Total: ${}", totalCost);
            
        } finally {
            TenantContext.clear();
        }
    }
    
    /**
     * Process call_analyzed event (AI analysis results)
     */
    public void processCallAnalyzed(Map<String, Object> payload) {
        String callId = (String) payload.get("call_id");
        log.info("🔍 Retell call analyzed - ID: {}", callId);
        
        // TODO: Store analysis results if needed
        log.debug("Analysis data: {}", payload.get("analysis"));
    }
    
    /**
     * Process agent_response event (real-time streaming)
     */
    public void processAgentResponse(Map<String, Object> payload) {
        String callId = (String) payload.get("call_id");
        String response = (String) payload.get("response");
        
        log.debug("💬 Retell agent response - Call: {}, Response: {}", callId, response);
        
        // Real-time event, usually just logged or streamed to frontend
    }
}
