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

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

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

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

                var res = await _context.AddAsync(model);

                await _context.SaveChangesAsync();

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