using MediatR;
using Microsoft.AspNetCore.Mvc;
using SocialService.API.Application.Commands;

namespace SocialService.API.Controllers;

/// <summary>
/// EN: Controller for managing user blocks.
/// VI: Controller để quản lý block users.
/// </summary>
[ApiController]
[Route("api/v1/[controller]")]
public class BlocksController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<BlocksController> _logger;

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

    /// <summary>
    /// EN: Block a user.
    /// VI: Block user.
    /// </summary>
    [HttpPost]
    [ProducesResponseType(typeof(BlockUserResult), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> BlockUser([FromBody] BlockUserRequest request)
    {
        var command = new BlockUserCommand(request.BlockerId, request.BlockedId, request.Reason);
        var result = await _mediator.Send(command);
        return CreatedAtAction(nameof(GetBlockedUsers), new { userId = request.BlockerId }, result);
    }

    /// <summary>
    /// EN: Unblock a user.
    /// VI: Bỏ block user.
    /// </summary>
    [HttpDelete]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> UnblockUser([FromBody] UnblockUserRequest request)
    {
        var command = new UnblockUserCommand(request.BlockerId, request.BlockedId);
        var result = await _mediator.Send(command);
        return Ok(new { success = result });
    }

    /// <summary>
    /// EN: Get list of blocked users.
    /// VI: Lấy danh sách users bị block.
    /// </summary>
    [HttpGet("users/{userId}")]
    [ProducesResponseType(typeof(GetBlockedUsersResult), StatusCodes.Status200OK)]
    public async Task<IActionResult> GetBlockedUsers(Guid userId, [FromQuery] int skip = 0, [FromQuery] int take = 20)
    {
        var query = new GetBlockedUsersQuery(userId, skip, take);
        var result = await _mediator.Send(query);
        return Ok(result);
    }
}

#region Request DTOs

public record BlockUserRequest(Guid BlockerId, Guid BlockedId, string? Reason = null);
public record UnblockUserRequest(Guid BlockerId, Guid BlockedId);

#endregion

#region Query Classes

public record GetBlockedUsersQuery(Guid UserId, int Skip = 0, int Take = 20) : IRequest<GetBlockedUsersResult>;
public record GetBlockedUsersResult(IEnumerable<BlockedUserDto> BlockedUsers, int TotalCount);
public record BlockedUserDto(Guid UserId, string DisplayName, string? AvatarUrl, DateTime BlockedAt, string? Reason);

#endregion
