const request = require('supertest');
const app = require('../index');
const mongoose = require('mongoose');
const User = require('../models/user');

beforeAll(async () => {
    await User.deleteMany(); 
  });
  
  afterAll(async () => {
    await mongoose.disconnect(); 
  });
  

describe('User API tests', () => {
  it('should create a new user', async () => {
    const res = await request(app)
      .post('/api/users/')
      .send({ username: 'testuser', email: 'test@example.com', age: 25 });
    expect(res.statusCode).toEqual(201);
    expect(res.body.username).toEqual('testuser');
    expect(res.body.email).toEqual('test@example.com');
    expect(res.body.age).toEqual(25);
  });

  it('should update an existing user', async () => {
    const newUser = await User.create({ username: 'updateuser', email: 'update@example.com', age: 30 });
    const res = await request(app)
      .put(`/api/users/${newUser._id}`)
      .send({ age: 35 });
    expect(res.statusCode).toEqual(200);
    expect(res.body.age).toEqual(35);
  });

  it('should get a list of users', async () => {
    const res = await request(app)
      .get('/api/users/');
    expect(res.statusCode).toEqual(200);
    expect(res.body.length).toBeGreaterThan(0);
  });
});