package com.saas.voip.controller;

import com.saas.voip.dto.request.CreateRetellAgentRequest;
import com.saas.voip.dto.response.RetellAgentResponse;
import com.saas.voip.service.provider.retell.RetellApiClient;
import com.saas.shared.dto.common.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * REST Controller for Retell AI agent management.
 * 
 * Path: /api/tenant/ai-assistants/retell
 * Role: TENANT_USER only
 * 
 * Endpoints:
 * - POST   /           Create new agent
 * - GET    /           List all agents
 * - GET    /{id}       Get agent details
 * - PUT    /{id}       Update agent
 * - DELETE /{id}       Delete agent
 */
@RestController
@RequestMapping("/api/tenant/ai-assistants/retell")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "Retell Agents", description = "Manage Retell AI agents")
@SecurityRequirement(name = "Bearer Authentication")
public class TenantRetellAgentController {

    private final RetellApiClient retellApiClient;

    @PostMapping
    @Operation(summary = "Create Retell agent", description = "Create new AI agent on Retell platform")
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "201",
            description = "Agent created successfully",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "Validation error"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "Unauthorized"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "Forbidden"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "503", description = "Retell API unavailable")
    })
    public ResponseEntity<ApiResponse<RetellAgentResponse>> createAgent(
            @Valid @RequestBody CreateRetellAgentRequest request) {
        log.info("Creating Retell agent: {}", request.getAgentName());

        RetellAgentResponse response = retellApiClient.createAgent(request);

        return ResponseEntity.status(HttpStatus.CREATED)
            .body(ApiResponse.success(response, "Retell agent created successfully"));
    }

    @GetMapping
    @Operation(summary = "List Retell agents", description = "Retrieve all agents from Retell")
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "200",
            description = "Agents retrieved successfully",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "Unauthorized"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "Forbidden"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "503", description = "Retell API unavailable")
    })
    public ResponseEntity<ApiResponse<List<RetellAgentResponse>>> listAgents() {
        log.info("Fetching Retell agents");

        List<RetellAgentResponse> agents = retellApiClient.listAgents();

        return ResponseEntity.ok()
            .body(ApiResponse.success(agents, "Retell agents retrieved successfully"));
    }

    @GetMapping("/{agentId}")
    @Operation(summary = "Get Retell agent", description = "Retrieve specific Retell agent by ID")
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "200",
            description = "Agent found",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "Unauthorized"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "Forbidden"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "Agent not found"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "503", description = "Retell API unavailable")
    })
    public ResponseEntity<ApiResponse<RetellAgentResponse>> getAgent(
            @Parameter(description = "Retell agent ID", example = "agent_abc123")
            @PathVariable String agentId) {
        log.info("Fetching Retell agent: {}", agentId);

        RetellAgentResponse response = retellApiClient.getAgent(agentId);

        return ResponseEntity.ok()
            .body(ApiResponse.success(response, "Retell agent retrieved successfully"));
    }

    @PutMapping("/{agentId}")
    @Operation(summary = "Update Retell agent", description = "Update existing Retell agent configuration")
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "200",
            description = "Agent updated successfully",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "Validation error"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "Unauthorized"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "Forbidden"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "Agent not found"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "503", description = "Retell API unavailable")
    })
    public ResponseEntity<ApiResponse<RetellAgentResponse>> updateAgent(
            @Parameter(description = "Retell agent ID", example = "agent_abc123")
            @PathVariable String agentId,
            @Valid @RequestBody CreateRetellAgentRequest request) {
        log.info("Updating Retell agent: {}", agentId);

        RetellAgentResponse response = retellApiClient.updateAgent(agentId, request);

        return ResponseEntity.ok()
            .body(ApiResponse.success(response, "Retell agent updated successfully"));
    }

    @DeleteMapping("/{agentId}")
    @Operation(summary = "Delete Retell agent", description = "Remove Retell agent")
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "204", description = "Agent deleted successfully"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "Unauthorized"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "Forbidden"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "Agent not found"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "503", description = "Retell API unavailable")
    })
    public ResponseEntity<Void> deleteAgent(
            @Parameter(description = "Retell agent ID", example = "agent_abc123")
            @PathVariable String agentId) {
        log.info("Deleting Retell agent: {}", agentId);

        retellApiClient.deleteAgent(agentId);

        return ResponseEntity.noContent().build();
    }
}
