// EN: Admin command to update a merchant's subscription plan.
// VI: Admin command để cập nhật gói đăng ký của merchant.

using MediatR;
using MerchantService.Domain.AggregatesModel.MerchantAggregate;

namespace MerchantService.API.Application.Commands.Admin;

/// <summary>
/// EN: Update a merchant's subscription plan (SuperAdmin only).
/// VI: Cập nhật gói đăng ký của merchant (chỉ SuperAdmin).
/// </summary>
public record UpdateMerchantPlanCommand(Guid MerchantId, int PlanId) : IRequest<UpdateMerchantPlanResult>;

public record UpdateMerchantPlanResult(bool Success, string PlanName, string? Error = null);

public class UpdateMerchantPlanCommandHandler : IRequestHandler<UpdateMerchantPlanCommand, UpdateMerchantPlanResult>
{
    private readonly IMerchantRepository _merchantRepository;
    private static readonly string[] PlanNames = ["Starter", "Growth", "Pro", "Enterprise"];

    public UpdateMerchantPlanCommandHandler(IMerchantRepository merchantRepository)
    {
        _merchantRepository = merchantRepository;
    }

    public async Task<UpdateMerchantPlanResult> Handle(
        UpdateMerchantPlanCommand request,
        CancellationToken cancellationToken)
    {
        if (request.PlanId < 0 || request.PlanId > 3)
            return new UpdateMerchantPlanResult(false, "", "Plan ID phải từ 0-3 (Starter/Growth/Pro/Enterprise)");

        var merchant = await _merchantRepository.GetByIdAsync(request.MerchantId, cancellationToken);
        if (merchant == null)
            return new UpdateMerchantPlanResult(false, "", "Merchant không tồn tại");

        merchant.UpdateSubscriptionPlan(request.PlanId);
        _merchantRepository.Update(merchant);
        await _merchantRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        var planName = PlanNames.ElementAtOrDefault(request.PlanId) ?? "Starter";
        return new UpdateMerchantPlanResult(true, planName);
    }
}
