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

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

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

        public async Task<ResponseModel> Handle(DeleteCounterpartyCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var res  = await _context.Counterparties.Where(x=>x.Id == request.Id).ExecuteDeleteAsync();

                if (res == 1)return new();

                return new()
                {
                    ErrorText = "Cannot find object to delete",
                    StatusCode = System.Net.HttpStatusCode.NotFound
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error on deleteing counterparty");
                return new()
                {
                    StatusCode = System.Net.HttpStatusCode.NotFound,
                    ErrorText = "Cannot delete counterparty"
                };
            }
        }
    }
}
