using MediatR;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Application.App.Stores.Services;
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 DeleteStoreCommandHandler(
    StoreContextService storeContextService,
    IStoreRepository storeRepository)
    : IRequestHandler<DeleteStoreCommand>
{
    /// <inheritdoc />
    public async Task Handle(DeleteStoreCommand request, CancellationToken cancellationToken)
    {
        // 1. 解析上下文
        var context = storeContextService.GetRequiredContext();

        // 2. 查询并校验门店归属
        var existing = await storeRepository.FindByIdAsync(request.Id, context.TenantId, cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "门店不存在");
        if (existing.MerchantId != context.MerchantId)
        {
            throw new BusinessException(ErrorCodes.Forbidden, "无权操作其他商户门店");
        }

        // 3. 执行删除
        await storeRepository.DeleteStoreAsync(existing.Id, context.TenantId, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
    }
}

