using AutoMapper;
using DSaC.Database;
using DSaC.Database.Models;
using DSaC.Models.DTOs;
using DSaC.Models.Internal;
using DSaC.Models.Internal.Сommands;
using MediatR;

namespace DSaC.Logic.Handlers.Commands
{
    public class UpdateCounterpartyCommandHandler: IRequestHandler<UpdateCounterpartyCommand, ResponseModel<CounterpartyViewDto>>
    {
        private readonly ILogger _logger;
        private readonly DsacContext _context;
        private readonly IMapper _mapper;

        public UpdateCounterpartyCommandHandler(ILogger<UpdateCounterpartyCommandHandler> logger, DsacContext context, IMapper mapper)
        {
            _logger = logger;
            _context = context;
            _mapper = mapper;
        }

        public async Task<ResponseModel<CounterpartyViewDto>> Handle(UpdateCounterpartyCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var model = _mapper.Map<Counterparty>(request.Model);

                var res = _context.Update(model);

                await _context.SaveChangesAsync();

                return new()
                {
                    Value = _mapper.Map<CounterpartyViewDto>(res.Entity)
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error on updating counterparty");
                return new()
                {
                    StatusCode = System.Net.HttpStatusCode.NotFound,
                    ErrorText = "Cannot update counterparty"
                };
            }
        }
    }
}
