// EN: Subscriptions Controller for subscription plan management.
// VI: Controller Subscriptions để quản lý gói đăng ký.

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

namespace MerchantService.API.Controllers;

/// <summary>
/// EN: Controller for subscription plan management.
/// VI: Controller để quản lý gói đăng ký.
/// </summary>
[ApiController]
[Route("api/v1/subscriptions")]
[Authorize]
public class SubscriptionsController : MerchantBaseController
{
    private readonly IMediator _mediator;
    private readonly ILogger<SubscriptionsController> _logger;

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

    /// <summary>
    /// EN: Get current merchant's subscription info.
    /// VI: Lấy thông tin gói đăng ký của merchant hiện tại.
    /// </summary>
    [HttpGet("me")]
    [ProducesResponseType(typeof(SubscriptionDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetSubscription(CancellationToken cancellationToken)
    {
        var userId = GetCurrentUserId();
        var result = await _mediator.Send(new GetSubscriptionQuery(userId), cancellationToken);
        if (result == null)
        {
            return NotFound(new { success = false, error = new { code = "SUBSCRIPTION_NOT_FOUND", message = "Merchant not found or not subscribed" } });
        }
        return Ok(new { success = true, data = result });
    }

    /// <summary>
    /// EN: Get all available subscription plans.
    /// VI: Lấy danh sách tất cả gói đăng ký có sẵn.
    /// </summary>
    [HttpGet("plans")]
    [AllowAnonymous]
    [ProducesResponseType(typeof(IReadOnlyList<SubscriptionPlanDto>), StatusCodes.Status200OK)]
    public async Task<IActionResult> GetPlans(CancellationToken cancellationToken)
    {
        var result = await _mediator.Send(new GetSubscriptionPlansQuery(), cancellationToken);
        return Ok(new { success = true, data = result });
    }

    /// <summary>
    /// EN: Subscribe or upgrade to a plan.
    /// VI: Đăng ký hoặc nâng cấp gói.
    /// </summary>
    [HttpPost("subscribe")]
    [ProducesResponseType(typeof(SubscribeCommandResult), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> Subscribe([FromBody] SubscribeCommand command, CancellationToken cancellationToken)
    {
        try
        {
            var userId = GetCurrentUserId();
            var cmd = command with { UserId = userId };
            var result = await _mediator.Send(cmd, cancellationToken);
            if (!result.Success)
            {
                return BadRequest(new { success = false, error = new { code = "SUBSCRIBE_FAILED", message = result.Message } });
            }
            return Ok(new { success = true, data = result });
        }
        catch (Domain.Exceptions.DomainException ex)
        {
            return BadRequest(new { success = false, error = new { code = "INVALID_PLAN", message = ex.Message } });
        }
    }

    /// <summary>
    /// EN: Get current usage vs plan limits.
    /// VI: Lấy mức sử dụng hiện tại so với giới hạn gói.
    /// </summary>
    [HttpGet("usage")]
    [ProducesResponseType(typeof(SubscriptionUsageDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetUsage(CancellationToken cancellationToken)
    {
        var userId = GetCurrentUserId();
        var result = await _mediator.Send(new GetSubscriptionUsageQuery(userId), cancellationToken);
        if (result == null)
        {
            return NotFound(new { success = false, error = new { code = "USAGE_NOT_FOUND", message = "Merchant not found" } });
        }
        return Ok(new { success = true, data = result });
    }
}
