using MediatR;
using TakeoutSaaS.Application.App.Products.Commands;
using TakeoutSaaS.Application.App.Products.Dto;
using TakeoutSaaS.Domain.Products.Entities;
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 SaveProductScheduleCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<SaveProductScheduleCommand, ProductScheduleItemDto>
{
    /// <inheritdoc />
    public async Task<ProductScheduleItemDto> Handle(SaveProductScheduleCommand request, CancellationToken cancellationToken)
    {
        // 1. 归一化并校验输入。
        var tenantId = tenantProvider.GetCurrentTenantId();
        var normalizedName = request.Name.Trim();
        if (string.IsNullOrWhiteSpace(normalizedName))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "规则名称不能为空");
        }

        if (!ProductScheduleMapping.TryParseStatus(request.Status, out var isEnabled))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "status 参数不合法");
        }

        if (!ProductScheduleMapping.TryParseTime(request.StartTime, out var startTime))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "开始时间格式必须为 HH:mm");
        }

        if (!ProductScheduleMapping.TryParseTime(request.EndTime, out var endTime))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "结束时间格式必须为 HH:mm");
        }

        if (startTime == endTime)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "开始和结束时间不能相同");
        }

        if (!ProductScheduleMapping.TryNormalizeWeekDays(request.WeekDays, out var normalizedWeekDays))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "请至少选择一个适用星期");
        }

        var normalizedProductIds = request.ProductIds
            .Where(item => item > 0)
            .Distinct()
            .ToList();
        var validProductIds = await productRepository.FilterExistingProductIdsAsync(
            tenantId,
            request.StoreId,
            normalizedProductIds,
            cancellationToken);
        if (validProductIds.Count == 0)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "请至少关联一个商品");
        }

        // 2. 校验门店内名称唯一。
        var isDuplicate = await productRepository.ExistsScheduleNameAsync(
            tenantId,
            request.StoreId,
            normalizedName,
            request.ScheduleId,
            cancellationToken);
        if (isDuplicate)
        {
            throw new BusinessException(ErrorCodes.Conflict, "规则名称已存在");
        }

        // 3. 创建或更新规则主记录。
        ProductSchedule schedule;
        if (!request.ScheduleId.HasValue)
        {
            schedule = new ProductSchedule
            {
                StoreId = request.StoreId,
                Name = normalizedName,
                StartTime = startTime,
                EndTime = endTime,
                WeekDaysMask = ProductScheduleMapping.ToWeekDaysMask(normalizedWeekDays),
                IsEnabled = isEnabled
            };

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

            existing.Name = normalizedName;
            existing.StartTime = startTime;
            existing.EndTime = endTime;
            existing.WeekDaysMask = ProductScheduleMapping.ToWeekDaysMask(normalizedWeekDays);
            existing.IsEnabled = isEnabled;
            schedule = existing;

            await productRepository.UpdateScheduleAsync(schedule, cancellationToken);
        }

        // 4. 替换规则关联商品。
        await productRepository.RemoveScheduleProductsAsync(schedule.Id, tenantId, request.StoreId, cancellationToken);
        var relations = validProductIds
            .Select(productId => new ProductScheduleProduct
            {
                StoreId = request.StoreId,
                ScheduleId = schedule.Id,
                ProductId = productId
            })
            .ToList();
        if (relations.Count > 0)
        {
            await productRepository.AddScheduleProductsAsync(relations, cancellationToken);
        }

        await productRepository.SaveChangesAsync(cancellationToken);

        // 5. 回读关联并返回最新快照。
        var latestRelations = await productRepository.GetScheduleProductsByScheduleIdsAsync(
            [schedule.Id],
            tenantId,
            request.StoreId,
            cancellationToken);
        var productIdsLookup = latestRelations
            .GroupBy(x => x.ScheduleId)
            .ToDictionary(group => group.Key, group => group.Select(item => item.ProductId).ToList());

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