package com.saas.admin.controller;

import com.saas.shared.dto.common.ApiResponse;
import com.saas.voip.service.RetellApiClient;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin/providers")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "Admin Provider Management", description = "APIs for managing and viewing providers")
@PreAuthorize("hasRole('SYSTEM_ADMIN')")
public class AdminProviderController {

    private final RetellApiClient retellApiClient;
    private final com.saas.voip.service.VapiService vapiService;
    private final com.saas.voip.service.TwilioApiClient twilioApiClient;
    private final com.saas.voip.service.TelnyxApiClient telnyxApiClient;

    private final com.saas.admin.repository.TenantAIConfigRepository aiConfigRepository;

    private final com.saas.admin.repository.TenantRepository tenantRepository;

    @GetMapping("/retell/agents")
    @Operation(summary = "List Retell AI Agents", description = "Fetch list of AI agents from Retell account with Tenant Info")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getRetellAgents() {
        try {
            // 1. Fetch Agents from Retell API
            List<Map<String, Object>> agents = retellApiClient.listAgents();

            // 2. Fetch all AI Configs from DB to find mappings
            List<com.saas.admin.entity.TenantAIConfig> configs = aiConfigRepository.findAll();

            // Map RetellAgentID -> TenantID
            Map<String, String> assistantToTenantMap = configs.stream()
                    .filter(c -> c.getRetellAgentId() != null)
                    .collect(Collectors.toMap(
                            com.saas.admin.entity.TenantAIConfig::getRetellAgentId,
                            com.saas.admin.entity.TenantAIConfig::getTenantId,
                            (existing, replacement) -> existing // Keep first if duplicate
                    ));

            // 3. Fetch all Tenants for Names
            Map<String, String> tenantIdToName = tenantRepository.findAll().stream()
                    .collect(Collectors.toMap(
                            com.saas.admin.entity.Tenant::getTenantId,
                            com.saas.admin.entity.Tenant::getTenantName));

            // 4. Merge Tenant Info into Agent Objects
            for (Map<String, Object> agent : agents) {
                String agentId = (String) agent.get("agent_id");
                if (agentId != null && assistantToTenantMap.containsKey(agentId)) {
                    String tenantId = assistantToTenantMap.get(agentId);
                    agent.put("tenantId", tenantId);
                    agent.put("tenantName", tenantIdToName.getOrDefault(tenantId, "Unknown"));
                } else {
                    agent.put("tenantId", null);
                    agent.put("tenantName", null);
                }
            }

            return ResponseEntity.ok(ApiResponse.success(agents));
        } catch (Exception e) {
            log.error("Failed to fetch retell agents", e);
            return ResponseEntity.ok(ApiResponse.error("Failed to fetch agents: " + e.getMessage()));
        }
    }

    @GetMapping("/vapi/assistants")
    @Operation(summary = "List Vapi Assistants", description = "Fetch list of Assistants from Vapi Account")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getVapiAssistants() {
        try {
            List<Map<String, Object>> assistants = vapiService.fetchAssistantsFromApi();
            return ResponseEntity.ok(ApiResponse.success(assistants));
        } catch (Exception e) {
            log.error("Failed to fetch Vapi assistants", e);
            return ResponseEntity.ok(ApiResponse.error("Failed to fetch Vapi assistants: " + e.getMessage()));
        }
    }

    @GetMapping("/twilio/numbers")
    @Operation(summary = "List Twilio Numbers", description = "Fetch list of Incoming Phone Numbers from Twilio")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getTwilioNumbers() {
        try {
            List<Map<String, Object>> numbers = twilioApiClient.listIncomingPhoneNumbers();
            return ResponseEntity.ok(ApiResponse.success(numbers));
        } catch (Exception e) {
            log.error("Failed to fetch Twilio numbers", e);
            return ResponseEntity.ok(ApiResponse.error("Failed to fetch Twilio numbers: " + e.getMessage()));
        }
    }

    @GetMapping("/telnyx/numbers")
    @Operation(summary = "List Telnyx Numbers", description = "Fetch list of Phone Numbers from Telnyx")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getTelnyxNumbers() {
        try {
            List<Map<String, Object>> numbers = telnyxApiClient.listPhoneNumbers();
            return ResponseEntity.ok(ApiResponse.success(numbers));
        } catch (Exception e) {
            log.error("Failed to fetch Telnyx numbers", e);
            return ResponseEntity.ok(ApiResponse.error("Failed to fetch Telnyx numbers: " + e.getMessage()));
        }
    }
}
