using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MiningService.API.Application.Commands;
using MiningService.API.Application.Queries;

namespace MiningService.API.Controllers;

/// <summary>
/// EN: Referrals controller.
/// VI: Controller cho giới thiệu.
/// </summary>
[ApiController]
[Route("api/v1/[controller]")]
[Authorize]
public class ReferralsController : ControllerBase
{
    private readonly IMediator _mediator;

    public ReferralsController(IMediator mediator)
    {
        _mediator = mediator;
    }

    /// <summary>
    /// EN: Get my referral code and referrals list.
    /// VI: Lấy mã giới thiệu và danh sách người được giới thiệu.
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(ReferralsDto), StatusCodes.Status200OK)]
    public async Task<IActionResult> GetReferrals([FromQuery] Guid userId, CancellationToken ct)
    {
        var result = await _mediator.Send(new GetReferralsQuery(userId), ct);
        return Ok(result);
    }

    /// <summary>
    /// EN: Apply a referral code.
    /// VI: Áp dụng mã giới thiệu.
    /// </summary>
    [HttpPost("apply")]
    [ProducesResponseType(typeof(ApplyReferralResult), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> ApplyReferralCode([FromBody] ApplyReferralRequest request, CancellationToken ct)
    {
        var result = await _mediator.Send(new ApplyReferralCodeCommand(request.UserId, request.ReferralCode), ct);
        return Ok(result);
    }

    /// <summary>
    /// EN: Get my referral code.
    /// VI: Lấy mã giới thiệu của tôi.
    /// </summary>
    [HttpGet("code")]
    [ProducesResponseType(typeof(ReferralCodeDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetReferralCode([FromQuery] Guid userId, CancellationToken ct)
    {
        var result = await _mediator.Send(new GetReferralCodeQuery(userId), ct);
        if (result == null) return NotFound();
        return Ok(result);
    }

    /// <summary>
    /// EN: Get referral statistics.
    /// VI: Lấy thống kê giới thiệu.
    /// </summary>
    [HttpGet("stats")]
    [ProducesResponseType(typeof(ReferralStatsDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetReferralStats([FromQuery] Guid userId, CancellationToken ct)
    {
        var result = await _mediator.Send(new GetReferralStatsQuery(userId), ct);
        if (result == null) return NotFound();
        return Ok(result);
    }
}

public record ApplyReferralRequest(Guid UserId, string ReferralCode);

