using HotelContracts.BindingModels;
using HotelContracts.BusinessLogicsContracts;
using HotelContracts.SearchModels;
using HotelContracts.StoragesContracts;
using HotelContracts.ViewModels;
using Microsoft.Extensions.Logging;

namespace HotelBusinessLogic.BusinessLogics;

public class ReservationLogic : IReservationLogic
{
    private readonly ILogger _logger;
    private readonly IReservationStorage _reservationStorage;

    public ReservationLogic(IReservationStorage reservationStorage, ILogger<ReservationLogic> logger)
    {
        _logger = logger;
        _reservationStorage = reservationStorage;
    }
    
    public List<ReservationViewModel>? ReadList(ReservationSearchModel? model)
    {
        var list = model == null ? _reservationStorage.GetFullList() : _reservationStorage.GetFilteredList(model);
        _logger.LogInformation("ReadList .Count:{Count}", list.Count);
        return list;
    }

    public ReservationViewModel? ReadElement(ReservationSearchModel model)
    {
        if (model == null)
            throw new ArgumentNullException(nameof(model));
        _logger.LogInformation("ReadElement .Id:{Id}", model.Id);
        var element = _reservationStorage.GetElement(model);
        if (element == null)
        {
            _logger.LogWarning("ReadElement element not found");
            return null;
        }
        _logger.LogInformation("ReadElement find .Id:{Id}", element.Id);
        return element;
    }

    public bool Create(ReservationBindingModel model)
    {
        CheckModel(model);
        if (_reservationStorage.Insert(model) != null) return true;
        _logger.LogWarning("Insert operation failed");
        return false;
    }

    public bool Update(ReservationBindingModel model)
    {
        CheckModel(model);
        if (_reservationStorage.Update(model) != null) return true;
        _logger.LogWarning("Update operation failed");
        return false;
    }

    public bool Delete(ReservationBindingModel model)
    {
        CheckModel(model);
        _logger.LogInformation("Delete .Id:{Id}", model.Id);
        if (_reservationStorage.Delete(model) != null) return true;
        _logger.LogWarning("Delete operation failed");
        return false;
    }

    private void CheckModel(ReservationBindingModel? model)
    {
        if (model == null)
            throw new ArgumentNullException(nameof(model));
        if (model.StartDate > model.EndDate)
            throw new ArgumentException("Start date must be early then end date");
        _logger.LogInformation("Reservation .Id:{Id}", model.Id);
    }
}