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

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

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

        public async Task<ResponseModel<ContractFullDto>> Handle(GetContractQuery request, CancellationToken cancellationToken)
        {
            try
            {
                var res = await _context.Contracts.FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken: cancellationToken);

                if (res == null)
                    return new()
                    {
                        StatusCode = System.Net.HttpStatusCode.NotFound,
                        ErrorText = "Contract with whit Id is not exist"
                    };
                var counterparty = await _mediator.Send(new GetConunterpartyQuery()
                {
                    Id = res.CounterpartyId
                }, cancellationToken: cancellationToken);

                if (counterparty.IsError)
                    return new()
                    {
                        StatusCode = System.Net.HttpStatusCode.NotFound,
                        ErrorText = counterparty.ErrorText
                    };

                var model = _mapper.Map<ContractFullDto>(res);
                model.Counterparty = counterparty.Value!;

                return new()
                {
                    Value = model,
                };

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

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