using MediatR;
using TakeoutSaaS.Application.App.Products.Commands;
using TakeoutSaaS.Application.App.Products.Dto;
using TakeoutSaaS.Domain.Products.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Products.Handlers;

/// <summary>
/// 修改商品时段规则状态命令处理器。
/// </summary>
public sealed class ChangeProductScheduleStatusCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<ChangeProductScheduleStatusCommand, ProductScheduleItemDto>
{
    /// <inheritdoc />
    public async Task<ProductScheduleItemDto> Handle(ChangeProductScheduleStatusCommand request, CancellationToken cancellationToken)
    {
        // 1. 解析状态并校验规则归属。
        if (!ProductScheduleMapping.TryParseStatus(request.Status, out var isEnabled))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "status 参数不合法");
        }

        var tenantId = tenantProvider.GetCurrentTenantId();
        var existing = await productRepository.FindScheduleByIdAsync(request.ScheduleId, tenantId, cancellationToken);
        if (existing is null || existing.StoreId != request.StoreId)
        {
            throw new BusinessException(ErrorCodes.NotFound, "时段规则不存在");
        }

        // 2. 保存状态变更。
        existing.IsEnabled = isEnabled;
        await productRepository.UpdateScheduleAsync(existing, cancellationToken);
        await productRepository.SaveChangesAsync(cancellationToken);

        // 3. 返回最新快照。
        var relations = await productRepository.GetScheduleProductsByScheduleIdsAsync(
            [existing.Id],
            tenantId,
            request.StoreId,
            cancellationToken);
        var productIdsLookup = relations
            .GroupBy(x => x.ScheduleId)
            .ToDictionary(group => group.Key, group => group.Select(item => item.ProductId).ToList());

        return ProductScheduleDtoFactory.ToDto(existing, productIdsLookup);
    }
}
