using MediatR;
using TakeoutSaaS.Application.App.Coupons.NewCustomer.Commands;
using TakeoutSaaS.Application.App.Coupons.NewCustomer.Dto;
using TakeoutSaaS.Domain.Coupons.Entities;
using TakeoutSaaS.Domain.Coupons.Enums;
using TakeoutSaaS.Domain.Coupons.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;

namespace TakeoutSaaS.Application.App.Coupons.NewCustomer.Handlers;

/// <summary>
/// 写入新客邀请记录处理器。
/// </summary>
public sealed class WriteNewCustomerInviteRecordCommandHandler(
    INewCustomerGiftRepository repository)
    : IRequestHandler<WriteNewCustomerInviteRecordCommand, NewCustomerInviteRecordDto>
{
    /// <inheritdoc />
    public async Task<NewCustomerInviteRecordDto> Handle(
        WriteNewCustomerInviteRecordCommand request,
        CancellationToken cancellationToken)
    {
        if (request.StoreId <= 0)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "storeId 参数不合法");
        }

        var inviterName = NewCustomerMapping.NormalizeDisplayName(request.InviterName, "inviterName");
        var inviteeName = NewCustomerMapping.NormalizeDisplayName(request.InviteeName, "inviteeName");
        var orderStatus = NewCustomerMapping.ParseInviteOrderStatus(request.OrderStatus);
        var rewardStatus = NewCustomerMapping.ParseInviteRewardStatus(request.RewardStatus);
        var sourceChannel = NewCustomerMapping.NormalizeOptionalText(request.SourceChannel, "sourceChannel", 32);

        var inviteTime = NewCustomerMapping.NormalizeUtc(request.InviteTime);
        DateTime? rewardIssuedAt = rewardStatus == NewCustomerInviteRewardStatus.Issued
            ? request.RewardIssuedAt.HasValue
                ? NewCustomerMapping.NormalizeUtc(request.RewardIssuedAt.Value)
                : DateTime.UtcNow
            : null;

        var entity = new NewCustomerInviteRecord
        {
            StoreId = request.StoreId,
            InviterName = inviterName,
            InviteeName = inviteeName,
            InviteTime = inviteTime,
            OrderStatus = orderStatus,
            RewardStatus = rewardStatus,
            RewardIssuedAt = rewardIssuedAt,
            SourceChannel = sourceChannel
        };

        await repository.AddInviteRecordAsync(entity, cancellationToken);
        await repository.SaveChangesAsync(cancellationToken);

        return NewCustomerMapping.ToInviteRecordDto(entity);
    }
}
