import supertest from 'supertest';
import { server, createTestUser, logInUser, id } from '../helpers';

describe('PATCH /auth/change-password', () => {
  it('should return 403 if user is not logged in', async () => {
    const res = await supertest(server)
      .patch('/api/v1/auth/change-password')
      .send();

    expect(res.status).toBe(403);
  });

  it('should return 400 if user does not pass in password details', async () => {
    const res = await supertest(server)
      .patch('/api/v1/auth/change-password')
      .set('Authorization', await logInUser())
      .send();

    expect(res.status).toBe(400);
  });

  it('should return 404 if user does not exist', async () => {
    const res = await supertest(server)
      .patch('/api/v1/auth/change-password')
      .set('Authorization', await logInUser())
      .send({
        oldPassword: 'password',
        newPassword: 'newPassword',
        confirmPassword: 'newPassword',
      });

    expect(res.status).toBe(404);
    expect(res.body).toMatchObject({
      success: false,
      message: 'invalid request',
    });
  });

  it('should return 403 if old password is invalid', async () => {
    const userId = id();
    await createTestUser({ _id: userId });

    const res = await supertest(server)
      .patch('/api/v1/auth/change-password')
      .set('Authorization', await logInUser({ _id: userId }))
      .send({
        oldPassword: 'password',
        newPassword: 'newPassword',
        confirmPassword: 'newPassword',
      });

    expect(res.status).toBe(403);
    expect(res.body).toMatchObject({
      success: false,
      message: 'Old password is incorrect',
    });
  });

  it('should return 201 and correct data', async () => {
    const userId = id();
    await createTestUser({ _id: userId, password: 'oldPassword' });

    const res = await supertest(server)
      .patch('/api/v1/auth/change-password')
      .set('Authorization', await logInUser({ _id: userId }))
      .send({
        oldPassword: 'oldPassword',
        newPassword: 'newPassword',
        confirmPassword: 'newPassword',
      });

    expect(res.status).toBe(201);
    expect(res.body).toMatchObject({
      success: true,
      message: 'password change successful',
    });
  });
});
