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

namespace HotelBusinessLogic.BusinessLogics;

public class GuestLogic : IGuestLogic
{
    private readonly IGuestStorage _guestStorage;
    private readonly ILogger _logger;

    public GuestLogic(IGuestStorage guestStorage, ILogger<GuestLogic> logger)
    {
        _logger = logger;
        _guestStorage = guestStorage;
    }
    
    public List<GuestViewModel>? ReadList(GuestSearchModel? model)
    {
        var list = model == null ? _guestStorage.GetFullList() : _guestStorage.GetFilteredList(model);
        _logger.LogInformation("ReadList .Count:{Count}", list.Count);
        return list;
    }

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

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

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

    private void CheckModel(GuestBindingModel? model, bool withParams = true)
    {
        if (model == null)
            throw new ArgumentNullException(nameof(model));
        if (!withParams)
            return;
        if (string.IsNullOrEmpty(model.Name))
            throw new ArgumentException("Name must be not null");
        if (string.IsNullOrEmpty(model.SecondName))
            throw new ArgumentException("Second name must be not null");
        if (string.IsNullOrEmpty(model.LastName))
            throw new ArgumentException("Last name must be not null");
    }
}