using CMSMicroservice.Application.Common.Exceptions;

namespace CMSMicroservice.Application.WarehouseCQ.Commands.SetDefaultWarehouse;

public class SetDefaultWarehouseCommandHandler : IRequestHandler<SetDefaultWarehouseCommand, SetDefaultWarehouseResponseDto>
{
    private readonly IApplicationDbContext _context;

    public SetDefaultWarehouseCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<SetDefaultWarehouseResponseDto> Handle(SetDefaultWarehouseCommand request, CancellationToken cancellationToken)
    {
        var warehouse = await _context.Warehouses
            .FirstOrDefaultAsync(w => w.Id == request.Id, cancellationToken);

        if (warehouse == null)
        {
            throw new NotFoundException(nameof(Domain.Entities.Warehouse), request.Id);
        }

        // ریست کردن همه انبارهای دیگر
        var otherWarehouses = await _context.Warehouses
            .Where(w => w.IsDefault && w.Id != request.Id)
            .ToListAsync(cancellationToken);

        foreach (var other in otherWarehouses)
        {
            other.IsDefault = false;
        }

        // تنظیم این انبار به عنوان پیش‌فرض
        warehouse.IsDefault = true;

        await _context.SaveChangesAsync(cancellationToken);

        return new SetDefaultWarehouseResponseDto { Success = true };
    }
}
