using Asp.Versioning;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using FacebookService.API.Application.Commands;
using FacebookService.API.Application.Queries;
using FacebookService.API.Application.Dtos;

namespace FacebookService.API.Controllers;

/// <summary>
/// EN: Controller for Chatbot Flow and AI Config management.
/// VI: Controller quản lý Chatbot Flow và AI Config.
/// </summary>
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/chatbots")]
[Produces("application/json")]
public class ChatbotsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<ChatbotsController> _logger;

    public ChatbotsController(IMediator mediator, ILogger<ChatbotsController> logger)
    {
        _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    #region Chatbot Flows

    /// <summary>
    /// EN: Get chatbot flows for a shop.
    /// VI: Lấy danh sách chatbot flows của shop.
    /// </summary>
    [HttpGet("flows")]
    [ProducesResponseType(typeof(IEnumerable<ChatbotFlowSummaryDto>), StatusCodes.Status200OK)]
    public async Task<IActionResult> GetFlows(
        [FromQuery] Guid shopId,
        [FromQuery] bool activeOnly = false)
    {
        var flows = await _mediator.Send(new GetChatbotFlowsQuery(shopId, activeOnly));
        return Ok(new { success = true, data = flows });
    }

    /// <summary>
    /// EN: Get a chatbot flow by ID.
    /// VI: Lấy chatbot flow theo ID.
    /// </summary>
    [HttpGet("flows/{id:guid}")]
    [ProducesResponseType(typeof(ChatbotFlowDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetFlow(Guid id)
    {
        var flow = await _mediator.Send(new GetChatbotFlowByIdQuery(id));

        if (flow is null)
        {
            return NotFound(new
            {
                success = false,
                error = new { code = "FLOW_NOT_FOUND", message = $"Chatbot flow with ID {id} not found" }
            });
        }

        return Ok(new { success = true, data = flow });
    }

    /// <summary>
    /// EN: Create a new chatbot flow.
    /// VI: Tạo chatbot flow mới.
    /// </summary>
    [HttpPost("flows")]
    [ProducesResponseType(typeof(CreateChatbotFlowCommandResult), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> CreateFlow([FromBody] CreateFlowRequest request)
    {
        var command = new CreateChatbotFlowCommand(
            request.ShopId,
            request.Name,
            request.TriggerType,
            request.TriggerValue);

        var result = await _mediator.Send(command);

        if (!result.Success)
        {
            return BadRequest(new
            {
                success = false,
                error = new { code = "FLOW_CREATE_FAILED", message = "Failed to create chatbot flow" }
            });
        }

        return CreatedAtAction(
            nameof(GetFlow),
            new { id = result.Id },
            new { success = true, data = result });
    }

    #endregion

    #region AI Config

    /// <summary>
    /// EN: Get AI chatbot config for a shop.
    /// VI: Lấy cấu hình AI chatbot của shop.
    /// </summary>
    [HttpGet("ai-config")]
    [ProducesResponseType(typeof(AIChatbotConfigDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetAIConfig([FromQuery] Guid shopId)
    {
        var config = await _mediator.Send(new GetAIChatbotConfigQuery(shopId));

        if (config is null)
        {
            return NotFound(new
            {
                success = false,
                error = new { code = "AI_CONFIG_NOT_FOUND", message = "AI config not found for this shop" }
            });
        }

        return Ok(new { success = true, data = config });
    }

    /// <summary>
    /// EN: Create or update AI chatbot config.
    /// VI: Tạo hoặc cập nhật cấu hình AI chatbot.
    /// </summary>
    [HttpPut("ai-config")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> UpsertAIConfig([FromBody] UpsertAIConfigRequest request)
    {
        var command = new UpsertAIChatbotConfigCommand(
            request.ShopId,
            request.Provider,
            request.Model,
            request.SystemPrompt,
            request.Temperature,
            request.MaxTokens);

        var result = await _mediator.Send(command);

        if (!result.Success)
        {
            return BadRequest(new
            {
                success = false,
                error = new { code = "AI_CONFIG_FAILED", message = "Failed to save AI config" }
            });
        }

        return Ok(new { 
            success = true, 
            data = result,
            message = result.IsNew ? "AI config created" : "AI config updated"
        });
    }

    #endregion
}

#region Request Models

public record CreateFlowRequest(
    Guid ShopId,
    string Name,
    string TriggerType,
    string TriggerValue
);

public record UpsertAIConfigRequest(
    Guid ShopId,
    string Provider,
    string Model,
    string SystemPrompt,
    float Temperature = 0.7f,
    int MaxTokens = 500
);

#endregion
