using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Domain.Stores.Entities;
using TakeoutSaaS.Domain.Stores.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 自提配置维护处理器。
/// </summary>
public sealed class UpsertStorePickupSettingCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<UpsertStorePickupSettingCommandHandler> logger)
    : IRequestHandler<UpsertStorePickupSettingCommand, StorePickupSettingDto>
{
    /// <inheritdoc />
    public async Task<StorePickupSettingDto> Handle(UpsertStorePickupSettingCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验门店存在
        var tenantId = tenantProvider.GetCurrentTenantId();
        var store = await storeRepository.FindByIdAsync(request.StoreId, tenantId, cancellationToken);
        if (store is null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "门店不存在");
        }

        // 2. 读取或创建配置
        var setting = await storeRepository.GetPickupSettingAsync(request.StoreId, tenantId, cancellationToken);
        if (setting is null)
        {
            setting = new StorePickupSetting
            {
                TenantId = tenantId,
                StoreId = request.StoreId
            };
            await storeRepository.AddPickupSettingAsync(setting, cancellationToken);
        }

        // 3. 更新字段
        setting.AllowToday = request.AllowToday;
        setting.AllowDaysAhead = request.AllowDaysAhead;
        setting.DefaultCutoffMinutes = request.DefaultCutoffMinutes;
        setting.MaxQuantityPerOrder = request.MaxQuantityPerOrder;
        setting.Mode = request.Mode;
        setting.FineRuleJson = request.FineRuleJson;
        await storeRepository.UpdatePickupSettingAsync(setting, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("更新门店 {StoreId} 自提配置", request.StoreId);
        return new StorePickupSettingDto
        {
            Id = setting.Id,
            StoreId = setting.StoreId,
            AllowToday = setting.AllowToday,
            AllowDaysAhead = setting.AllowDaysAhead,
            DefaultCutoffMinutes = setting.DefaultCutoffMinutes,
            MaxQuantityPerOrder = setting.MaxQuantityPerOrder,
            Mode = setting.Mode,
            FineRuleJson = setting.FineRuleJson
        };
    }
}
