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

namespace HotelBusinessLogic.BusinessLogics;

public class CleaningInstrumentsLogic : ICleaningInstrumentsLogic
{
    private readonly ICleaningInstrumentsStorage _cleaningInstruments;
    private readonly ILogger _logger;

    public CleaningInstrumentsLogic(ICleaningInstrumentsStorage cleaningInstruments, ILogger logger)
    {
        _cleaningInstruments = cleaningInstruments;
        _logger = logger;
    }

    public List<CleaningInstrumentsViewModel>? ReadList(CleaningInstrumentsSearchModel? model)
    {
        var list = model == null ? _cleaningInstruments.GetFullList() : _cleaningInstruments.GetFilteredList(model);
        _logger.LogInformation("ReadList .Count:{Count}", list.Count);
        return list;
    }

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

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

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

    private void CheckModel(CleaningInstrumentsBindingModel? model, bool withParams = true)
    {
        if (model == null)
            throw new ArgumentNullException(nameof(model));
        if (!withParams)
            return;
        if (string.IsNullOrEmpty(model.Type))
            throw new ArgumentException("Type must be not null");
    }
}