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

namespace HotelBusinessLogic.BusinessLogics;

public class RoomLogic : IRoomLogic
{
    private readonly IRoomStorage _roomStorage;
    private readonly ILogger _logger;

    public RoomLogic(IRoomStorage roomStorage, ILogger<RoomLogic> logger)
    {
        _logger = logger;
        _roomStorage = roomStorage;
    }
    
    public List<RoomViewModel>? ReadList(RoomSearchModel? model)
    {
        var list = model == null ? _roomStorage.GetFullList() : _roomStorage.GetFilteredList(model);
        _logger.LogInformation("ReadList .Count:{Count}", list.Count);
        return list;
    }

    public RoomViewModel? ReadElement(RoomSearchModel model)
    {
        if (model == null)
            throw new ArgumentNullException(nameof(model));
        _logger.LogInformation("ReadElement .Id:{Id} .Type:{Type} .Cost:{Cost}", 
            model.Id, model.Type, model.Cost);
        var element = _roomStorage.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(RoomBindingModel model)
    {
        CheckModel(model);
        if (_roomStorage.Insert(model) != null) return true;
        _logger.LogWarning("Insert operation failed");
        return false;

    }

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

    }

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

    private void CheckModel(RoomBindingModel? model)
    {
        if (model == null) 
            throw new ArgumentNullException(nameof(model));
        if (string.IsNullOrEmpty(model.Type)) 
            throw new ArgumentException("Type must be not null");
        _logger.LogInformation("Room .Id:{Id} .Type:{Type} .Cost:{Cost}", 
            model.Id, model.Type, model.Cost);
    }
}