import { defineEventHandler, readBody } from 'h3';

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;
  const id = parseInt(event.context.params?.id, 10);

  if (isNaN(id)) {
    throw createError({ statusCode: 400, statusMessage: 'Invalid user ID' });
  }

  const userIndex = users.findIndex((user) => user.id === id);

  if (method === 'GET') {
    // Get user by ID
    const user = users.find((user) => user.id === id);
    if (!user) {
      throw createError({ statusCode: 404, statusMessage: 'User not found' });
    }
    return user;
  }

  if (method === 'PUT') {
    // Update user by ID
    if (userIndex === -1) {
      throw createError({ statusCode: 404, statusMessage: 'User not found' });
    }
    const body = await readBody(event);
    users[userIndex] = { ...users[userIndex], ...body };
    return { message: 'User updated', user: users[userIndex] };
  }

  if (method === 'DELETE') {
    // Delete user by ID
    if (userIndex === -1) {
      throw createError({ statusCode: 404, statusMessage: 'User not found' });
    }
    users.splice(userIndex, 1);
    return { message: 'User deleted' };
  }

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