package com.saas.admin.controller;

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.*;

import java.util.Map;

/**
 * Admin Retell AI Controller
 * 
 * Phase 4.3 - Admin oversight for Retell AI agents
 * 
 * Provides SYSTEM_ADMIN with:
 * - Global agent listing across all tenants
 * - Agent management (create, update, delete)
 * - Call monitoring and analytics
 * 
 * Security: Only SYSTEM_ADMIN can access
 */
@RestController
@RequestMapping("/api/admin/retell")
@PreAuthorize("hasRole('SYSTEM_ADMIN')")
@Tag(name = "Admin Retell AI", description = "Admin oversight for Retell AI")
@RequiredArgsConstructor
@Slf4j
public class AdminRetellController {
    
    private final RetellApiClient retellApiClient;
    
    /**
     * List all Retell agents (global admin view)
     */
    @GetMapping("/agents")
    @Operation(summary = "List all Retell agents", description = "Admin view of all Retell agents across tenants")
    public ResponseEntity<?> listAllAgents() {
        log.info("📋 Admin listing all Retell agents");
        
        try {
            Map<String, Object> agents = retellApiClient.listAgents();
            return ResponseEntity.ok(agents);
            
        } catch (Exception e) {
            log.error("❌ Failed to list Retell agents", e);
            return ResponseEntity.internalServerError()
                .body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * Get specific agent details
     */
    @GetMapping("/agents/{agentId}")
    @Operation(summary = "Get Retell agent details")
    public ResponseEntity<?> getAgent(@PathVariable String agentId) {
        log.info("🔍 Admin fetching Retell agent: {}", agentId);
        
        try {
            // TODO: Implement getAgent in RetellApiClient
            return ResponseEntity.ok(Map.of("message", "Agent details", "agentId", agentId));
            
        } catch (Exception e) {
            log.error("❌ Failed to fetch Retell agent", e);
            return ResponseEntity.internalServerError()
                .body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * Delete Retell agent (admin override)
     */
    @DeleteMapping("/agents/{agentId}")
    @Operation(summary = "Delete Retell agent", description = "Admin can delete any agent")
    public ResponseEntity<?> deleteAgent(@PathVariable String agentId) {
        log.warn("🗑️ Admin deleting Retell agent: {}", agentId);
        
        try {
            retellApiClient.deleteAgent(agentId);
            return ResponseEntity.ok(Map.of("message", "Agent deleted successfully"));
            
        } catch (Exception e) {
            log.error("❌ Failed to delete Retell agent", e);
            return ResponseEntity.internalServerError()
                .body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * Get Retell call details (admin monitoring)
     */
    @GetMapping("/calls/{callId}")
    @Operation(summary = "Get Retell call details", description = "Admin can view any call")
    public ResponseEntity<?> getCallDetails(@PathVariable String callId) {
        log.info("📞 Admin fetching Retell call: {}", callId);
        
        try {
            Map<String, Object> callDetails = retellApiClient.getCallDetails(callId);
            return ResponseEntity.ok(callDetails);
            
        } catch (Exception e) {
            log.error("❌ Failed to fetch Retell call details", e);
            return ResponseEntity.internalServerError()
                .body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * Terminate active call (admin emergency stop)
     */
    @PostMapping("/calls/{callId}/terminate")
    @Operation(summary = "Terminate Retell call", description = "Admin emergency call termination")
    public ResponseEntity<?> terminateCall(@PathVariable String callId) {
        log.warn("🛑 Admin terminating Retell call: {}", callId);
        
        try {
            retellApiClient.terminateCall(callId);
            return ResponseEntity.ok(Map.of("message", "Call terminated successfully"));
            
        } catch (Exception e) {
            log.error("❌ Failed to terminate Retell call", e);
            return ResponseEntity.internalServerError()
                .body(Map.of("error", e.getMessage()));
        }
    }
}
