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 UpdateStoreBusinessHourCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<UpdateStoreBusinessHourCommandHandler> logger)
    : IRequestHandler<UpdateStoreBusinessHourCommand, StoreBusinessHourDto?>
{
    private readonly IStoreRepository _storeRepository = storeRepository;
    private readonly ITenantProvider _tenantProvider = tenantProvider;
    private readonly ILogger<UpdateStoreBusinessHourCommandHandler> _logger = logger;

    /// <inheritdoc />
    public async Task<StoreBusinessHourDto?> Handle(UpdateStoreBusinessHourCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取时段
        var tenantId = _tenantProvider.GetCurrentTenantId();
        var existing = await _storeRepository.FindBusinessHourByIdAsync(request.BusinessHourId, tenantId, cancellationToken);
        if (existing is null)
        {
            return null;
        }

        // 2. 校验门店归属
        if (existing.StoreId != request.StoreId)
        {
            throw new BusinessException(ErrorCodes.ValidationFailed, "营业时段不属于该门店");
        }

        // 3. 更新字段
        existing.DayOfWeek = request.DayOfWeek;
        existing.HourType = request.HourType;
        existing.StartTime = request.StartTime;
        existing.EndTime = request.EndTime;
        existing.CapacityLimit = request.CapacityLimit;
        existing.Notes = request.Notes?.Trim();

        // 4. 持久化
        await _storeRepository.UpdateBusinessHourAsync(existing, cancellationToken);
        await _storeRepository.SaveChangesAsync(cancellationToken);
        _logger.LogInformation("更新营业时段 {BusinessHourId} 对应门店 {StoreId}", existing.Id, existing.StoreId);

        // 5. 返回 DTO
        return StoreMapping.ToDto(existing);
    }
}
