// User data store: CRUD helpers and seed data

#include "api/users/store.hpp"

// Find a user by ID, returns nullptr if not found
user_t *find_user(uint8 id)
{
  for (int i = 0; i < MAX_USERS; i++)
  {
    if (g_Users[i].active && g_Users[i].id == id)
    {
      return &g_Users[i];
    }
  }
  return nullptr;
}

// Add a user, returns pointer to new user or nullptr if full
user_t *add_user(const char *name)
{
  for (int i = 0; i < MAX_USERS; i++)
  {
    if (!g_Users[i].active)
    {
      g_Users[i].id = g_NextUserId++;
      strlcpy(g_Users[i].name, name, sizeof(g_Users[i].name));
      g_Users[i].active = true;
      return &g_Users[i];
    }
  }
  return nullptr;
}

// Remove a user by ID, returns true if found and removed
bool remove_user(uint8 id)
{
  for (int i = 0; i < MAX_USERS; i++)
  {
    if (g_Users[i].active && g_Users[i].id == id)
    {
      g_Users[i].active = false;
      g_Users[i].id = 0;
      g_Users[i].name[0] = '\0';
      return true;
    }
  }
  return false;
}

// Update a user's name, returns pointer to user or nullptr if not found
user_t *update_user(uint8 id, const char *name)
{
  user_t *user = find_user(id);
  if (user)
  {
    strlcpy(user->name, name, sizeof(user->name));
  }
  return user;
}

// Populate dummy users on boot for development iteration
void seed_users()
{
  add_user("Alice");
  add_user("Bob");
  add_user("Charlie");
}
