package com.saas.voip.controller;

import com.saas.admin.entity.PhoneNumber;
import com.saas.admin.entity.Tenant;
import com.saas.admin.repository.PhoneNumberRepository;
import com.saas.admin.repository.TenantRepository;
import com.saas.shared.core.TenantContext;
import com.saas.shared.enums.Provider;
import com.saas.tenant.service.InboundCallService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

/**
 * Controller for handling Telnyx SMS delivery status callbacks
 * Similar to TwilioSmsCallbackController but for Telnyx provider
 */
@RestController
@RequestMapping("/api/voip/telnyx/sms")
@Slf4j
@RequiredArgsConstructor
public class TelnyxSmsCallbackController {

    private final InboundCallService inboundCallService;
    private final PhoneNumberRepository phoneNumberRepository;
    private final TenantRepository tenantRepository;

    @PostMapping("/status-callback")
    public ResponseEntity<String> handleSmsStatusCallback(@RequestBody Map<String, Object> payload) {
        
        try {
            log.info("=== TELNYX SMS STATUS CALLBACK ===");
            
            Map<String, Object> data = (Map<String, Object>) payload.get("data");
            Map<String, Object> webhookPayload = (Map<String, Object>) data.get("payload");
            
            String messageId = (String) webhookPayload.get("id");
            String status = (String) webhookPayload.get("delivery_status");
            String to = (String) webhookPayload.get("to");
            String from = (String) webhookPayload.get("from");
            
            log.info("📨 SMS Status Update - ID: {}, Status: {}, To: {}, From: {}", messageId, status, to, from);
            
            // STEP 1: Identify tenant via Telnyx phone number (From)
            TenantContext.setTenantId("admin");
            
            Optional<PhoneNumber> phoneNumberOpt = phoneNumberRepository.findByPhoneNumber(from);
            
            if (phoneNumberOpt.isEmpty() || phoneNumberOpt.get().getProvider() != Provider.TELNYX) {
                log.warn("⚠️ Numéro Telnyx inconnu: {} - Impossible d'identifier le tenant", from);
                return ResponseEntity.ok("OK");
            }
            
            PhoneNumber phoneNumber = phoneNumberOpt.get();
            String tenantId = phoneNumber.getTenantId();
            
            // STEP 2: Get tenant schema
            Optional<Tenant> tenantOpt = tenantRepository.findByTenantId(tenantId);
            
            if (tenantOpt.isEmpty()) {
                log.warn("⚠️ Tenant inconnu: {}", tenantId);
                return ResponseEntity.ok("OK");
            }
            
            String schemaName = tenantOpt.get().getSchemaName();
            log.info("🔄 Switching to tenant schema: {}", schemaName);
            
            // STEP 3: Switch tenant context and update SMS status
            TenantContext.setTenantId(schemaName);
            
            // Update SMS status in InboundCallRequest
            inboundCallService.updateSmsStatus(messageId, status);
            
            log.info("✅ SMS status updated successfully in tenant schema: {}", schemaName);
            
            return ResponseEntity.ok("OK");
            
        } catch (Exception e) {
            log.error("❌ Error processing Telnyx SMS callback", e);
            return ResponseEntity.ok("OK");
        } finally {
            TenantContext.clear();
        }
    }

    @GetMapping("/health")
    public String health() {
        return "Telnyx SMS Callback Service is running!";
    }
}
