package com.saas.shared.service;

import com.saas.tenant.entity.InboundCallData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

/**
 * Service to handle call data persistence asynchronously.
 * This prevents webhook timeouts (Twilio/Telnyx require < 5s response).
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AsyncCallService {

    private final DualSaveCallDataService dualSaveCallDataService;
    private final com.saas.tenant.service.InboundCallService inboundCallService;

    @Async
    public CompletableFuture<Void> saveCallDataAsync(InboundCallData callData, String schemaName, String tenantId) {
        log.info("🔄 [Async] Starting call data save for CallSid: {}", callData.getCallSid());
        try {
            dualSaveCallDataService.saveToBothDatabases(callData, schemaName, tenantId);
            log.info("✅ [Async] Completed call data save for CallSid: {}", callData.getCallSid());
        } catch (Exception e) {
            log.error("❌ [Async] Failed to save call data for CallSid: {}", callData.getCallSid(), e);
        }
        return CompletableFuture.completedFuture(null);
    }

    @Async
    public CompletableFuture<Void> saveInBoundCallAsync(InboundCallData callData, String tenantId, String schemaName) {
        log.info("🔄 [Async] Starting inbound call save for CallSid: {}", callData.getCallSid());
        try {
            inboundCallService.saveInBothDatabases(callData, tenantId, schemaName);
            log.info("✅ [Async] Completed inbound call save for CallSid: {}", callData.getCallSid());
        } catch (Exception e) {
            log.error("❌ [Async] Failed to save inbound call for CallSid: {}", callData.getCallSid(), e);
        }
        return CompletableFuture.completedFuture(null);
    }
}
