using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MktZaloService.API.Application.Commands.Rules;
using MktZaloService.API.Application.Queries.Rules;
using MktZaloService.Domain.Enums;

namespace MktZaloService.API.Controllers;

/// <summary>
/// EN: Controller for managing chatbot rules.
/// VI: Controller để quản lý quy tắc chatbot.
/// </summary>
[ApiController]
[Route("api/v1/chatbot-rules")]
[Authorize]
public class ChatbotRulesController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<ChatbotRulesController> _logger;

    public ChatbotRulesController(IMediator mediator, ILogger<ChatbotRulesController> logger)
    {
        _mediator = mediator;
        _logger = logger;
    }

    /// <summary>
    /// EN: Get all chatbot rules.
    /// VI: Lấy tất cả quy tắc chatbot.
    /// </summary>
    [HttpGet]
    public async Task<ActionResult<List<ChatbotRuleDto>>> GetRules(
        [FromQuery] bool includeInactive = false,
        CancellationToken ct = default)
    {
        var query = new GetChatbotRulesQuery(includeInactive);
        var result = await _mediator.Send(query, ct);
        return Ok(result);
    }

    /// <summary>
    /// EN: Create a new chatbot rule.
    /// VI: Tạo quy tắc chatbot mới.
    /// </summary>
    [HttpPost]
    public async Task<ActionResult<CreateChatbotRuleResult>> CreateRule(
        [FromBody] CreateRuleRequest request,
        CancellationToken ct = default)
    {
        var command = new CreateChatbotRuleCommand(
            request.Name,
            request.Description,
            Enum.Parse<RuleType>(request.Type),
            request.Priority,
            Enum.Parse<ActionType>(request.ActionType),
            request.ResponseText,
            request.TemplateId,
            request.Conditions.Select(c => new RuleConditionDto(c.Field, c.Operator, c.Value)).ToList()
        );

        var result = await _mediator.Send(command, ct);

        if (!result.Success)
        {
            return BadRequest(new { error = result.Error });
        }

        _logger.LogInformation(
            "EN: Created rule {RuleId}. VI: Đã tạo quy tắc {RuleId}",
            result.RuleId);

        return CreatedAtAction(nameof(GetRules), new { id = result.RuleId }, result);
    }

    /// <summary>
    /// EN: Delete a chatbot rule.
    /// VI: Xóa quy tắc chatbot.
    /// </summary>
    [HttpDelete("{id:guid}")]
    public async Task<IActionResult> DeleteRule(
        Guid id,
        CancellationToken ct = default)
    {
        var command = new DeleteChatbotRuleCommand(id);
        var result = await _mediator.Send(command, ct);

        if (!result.Success)
        {
            return NotFound(new { error = result.Error });
        }

        return NoContent();
    }

    /// <summary>
    /// EN: Toggle chatbot rule active status.
    /// VI: Bật/tắt trạng thái hoạt động quy tắc chatbot.
    /// </summary>
    [HttpPatch("{id:guid}/toggle")]
    public async Task<IActionResult> ToggleRule(
        Guid id,
        [FromQuery] bool activate,
        CancellationToken ct = default)
    {
        var command = new ToggleChatbotRuleCommand(id, activate);
        var result = await _mediator.Send(command, ct);

        if (!result.Success)
        {
            return BadRequest(new { error = result.Error });
        }

        return NoContent();
    }
}

/// <summary>
/// EN: Request to create a chatbot rule.
/// VI: Request để tạo quy tắc chatbot.
/// </summary>
public record CreateRuleRequest(
    string Name,
    string? Description,
    string Type,
    int Priority,
    string ActionType,
    string? ResponseText,
    Guid? TemplateId,
    List<ConditionRequest> Conditions
);

public record ConditionRequest(string Field, string Operator, string Value);
