namespace ServerManagement.Models
{
  public static class ToDoItemsRepository
  {
    private static List<ToDoItem> items = new List<ToDoItem>()
    {
      new ToDoItem { Id = 1, Name = "Update firmware of Brocade ICX 6430." },
      new ToDoItem { Id = 2, Name = "Fix bug with missing icons on Windows server." },
      new ToDoItem { Id = 3, Name = "Install Docker hub on Server D." },
      new ToDoItem { Id = 4, Name = "Upgrade VM RAM." },
      new ToDoItem { Id = 5, Name = "Investigate disk size of Debian server." },
    };

    public static void AddItem(ToDoItem item)
    {
      var maxId = items.Max(s => s.Id);
      item.Id = (items.Count > 0) ? maxId + 1 : 1;
      items.Add(item);      
    }

    public static List<ToDoItem> GetItems()
    {
      var sortedItems = items
        .OrderBy(item => item.IsCompleted)
        .ThenByDescending(item => item.Id)
        .ToList();
      return sortedItems;
    }

    public static ToDoItem? GetItemById(int id)
    {
      var item = items.FirstOrDefault(item => item.Id == id);
      if (item != null)
      {
        return new ToDoItem { Id = item.Id, Name = item.Name };
      }
      return null;
    }

    public static void UpdateItem(int itemId, ToDoItem item)
    {
      if (itemId != item.Id) return;

      var itemToUpdate = items.FirstOrDefault(item => item.Id == itemId);
      if (itemToUpdate != null)
      {
        itemToUpdate.Name = item.Name;
      }
    }

    public static void DeleteItem(int itemId)
    {
      var itemToDelete = items.FirstOrDefault(item => item.Id == itemId);
      if (itemToDelete != null)
      {
        items.Remove(itemToDelete);
      }
    }

    public static List<ToDoItem> SearchItems(string itemFilter)
    {
      return items.Where(item => item.Name.Contains(itemFilter, StringComparison.OrdinalIgnoreCase))
                  .ToList();
    }
  }
}