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

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 更新门店命令处理器。
/// </summary>
public sealed class UpdateStoreCommandHandler(
    IStoreRepository storeRepository,
    ILogger<UpdateStoreCommandHandler> logger)
    : IRequestHandler<UpdateStoreCommand, StoreDto?>
{
    /// <inheritdoc />
    public async Task<StoreDto?> Handle(UpdateStoreCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取门店
        var existing = await storeRepository.FindByIdAsync(request.StoreId, null, cancellationToken);
        if (existing == null)
        {
            return null;
        }

        // 2. 校验状态是否允许更新
        if (existing.AuditStatus == StoreAuditStatus.Pending)
        {
            throw new BusinessException(ErrorCodes.Conflict, "门店审核中，暂不允许修改");
        }

        // 2.1 (空行后) 强制关闭门店禁止更新
        if (existing.BusinessStatus == StoreBusinessStatus.ForceClosed)
        {
            throw new BusinessException(ErrorCodes.Conflict, "门店已被强制关闭，暂不允许修改");
        }

        // 3. (空行后) 更新字段
        existing.MerchantId = request.MerchantId;
        existing.Code = request.Code.Trim();
        existing.Name = request.Name.Trim();
        existing.Phone = request.Phone?.Trim();
        existing.ManagerName = request.ManagerName?.Trim();
        existing.Status = request.Status;
        existing.SignboardImageUrl = request.SignboardImageUrl?.Trim();
        existing.CategoryId = request.CategoryId;
        existing.Province = request.Province?.Trim();
        existing.City = request.City?.Trim();
        existing.District = request.District?.Trim();
        existing.Address = request.Address?.Trim();
        existing.Longitude = request.Longitude;
        existing.Latitude = request.Latitude;
        existing.Announcement = request.Announcement?.Trim();
        existing.Tags = request.Tags?.Trim();
        existing.DeliveryRadiusKm = request.DeliveryRadiusKm;
        existing.SupportsDineIn = request.SupportsDineIn;
        existing.SupportsPickup = request.SupportsPickup;
        existing.SupportsDelivery = request.SupportsDelivery;
        existing.SupportsReservation = request.SupportsReservation;
        existing.SupportsQueueing = request.SupportsQueueing;

        // 4. (空行后) 持久化
        await storeRepository.UpdateStoreAsync(existing, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("更新门店 {StoreId} - {StoreName}", existing.Id, existing.Name);

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