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

namespace DSaC_second.Logic.Handlers.Commands
{
    public class UpdateContractCommandHandler : IRequestHandler<UpdateContractCommand, ResponseModel<ContractFullDto>>
    {
        private readonly ILogger _logger;
        private readonly DsacContext _context;
        private readonly IMapper _mapper;
        private readonly IMediator _mediator;

        public UpdateContractCommandHandler(ILogger<UpdateContractCommandHandler> logger, DsacContext context, IMapper mapper, IMediator mediator)
        {
            _logger = logger;
            _context = context;
            _mapper = mapper;
            _mediator = mediator;
        }

        public async Task<ResponseModel<ContractFullDto>> Handle(UpdateContractCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var counterparty = await _mediator.Send(new GetConunterpartyQuery()
                {
                    Id = request.Model.CounterpartyId,
                }, cancellationToken: cancellationToken);

                if (counterparty.IsError)
                    return new()
                    {
                        StatusCode = System.Net.HttpStatusCode.NotFound,
                        ErrorText = counterparty.ErrorText,
                    };
                if(counterparty.Value == null)
                    return new()
                    {
                        StatusCode = System.Net.HttpStatusCode.NotFound,
                        ErrorText = "Cpty with this id not found",
                    };

                var model = _mapper.Map<Contract>(request.Model);

                _context.Contracts.Update(model);

                await _context.SaveChangesAsync(cancellationToken: cancellationToken);

                var res = _mapper.Map<ContractFullDto>(model);

                res.Counterparty = counterparty.Value!;

                return new() 
                { 
                    Value = res 
                };

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error on updating record");

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