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

namespace DSaC_second.Logic.Handlers.Commands
{
    public class DeleteContractCommandHandler: IRequestHandler<DeleteContractCommand, ResponseModel>
    {
        private readonly ILogger _logger;
        private readonly DsacContext _context;
        private readonly IMapper _mapper;

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

        public async Task<ResponseModel> Handle(DeleteContractCommand request, CancellationToken cancellationToken)
        {
            try
            {
                await _context.Contracts.Where(x => x.Id == request.Id).ExecuteDeleteAsync(cancellationToken);
                
                return new();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error on deleting record");

                return new()
                {
                    StatusCode = System.Net.HttpStatusCode.NotFound,
                    ErrorText = "Cannot delete contract by id",
                };
            }
        }
    }
}
