import { defineEventHandler, getQuery, readBody } from 'h3';

// In-memory "database" for demonstration
const users = [
  { id: 1, name: 'Alice', email: 'alice@example.com' },
  { id: 2, name: 'Bob', email: 'bob@example.com' },
];

export default defineEventHandler(async (event) => {
  const method = event.node.req.method;

  if (method === 'GET') {
    // Get all users
    const query = getQuery(event);
    const search = query.search?.toString();
    if (search) {
      return users.filter((user) =>
        user.name.toLowerCase().includes(search.toLowerCase())
      );
    }
    return users;
  }

  if (method === 'POST') {
    // Create a new user
    const body = await readBody(event);
    if (!body.name || !body.email) {
      throw createError({ statusCode: 400, statusMessage: 'Name and email are required' });
    }
    const newUser = { id: users.length + 1, ...body };
    users.push(newUser);
    return { message: 'User created', user: newUser };
  }

  throw createError({ statusCode: 405, statusMessage: 'Method not allowed' });
});
