import supertest from 'supertest';
import nock from 'nock';
import { server } from '../helpers';
import { Company, User } from '../../src/models';

const email = 'abc@email.com';
const password = '12345678';
const companyName = 'Dre';
const rcNumber = 'bn 12345';
const address = 'lekki, lagos';
const phoneNumber = '+2348012345678';

describe('POST /auth/signup', () => {
  it('should return 400 if required fields are not passed', async () => {
    const res = await supertest(server).post('/api/v1/auth/signup').send();

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

  it('should return 400 if passwords fields do not match', async () => {
    const res = await supertest(server).post('/api/v1/auth/signup').send({
      email,
      password,
      confirmPassword: '1234568',
      companyName,
      rcNumber,
      address,
      phoneNumber,
    });

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

  it('should return the correct response', async () => {
    nock(process.env.NOTIFICATION_SERVICE_URL!)
      .post('/send-email')
      .reply(200, {});

    const res = await supertest(server).post('/api/v1/auth/signup').send({
      email,
      password,
      confirmPassword: password,
      companyName,
      rcNumber,
      address,
      phoneNumber,
    });

    expect(res.status).toBe(201);
    expect(res.body).toMatchObject({
      success: true,
      message:
        'signup successful, please check your email for email verification',
    });
  });

  it('should return 500 if email service fails', async () => {
    const res = await supertest(server).post('/api/v1/auth/signup').send({
      email,
      password,
      confirmPassword: password,
      companyName,
      rcNumber,
      address,
      phoneNumber,
    });

    expect(res.status).toBe(500);
    expect(res.body).toMatchObject({
      success: false,
      message:
        'Sending Email verification link failed. Re-request Email verification link',
    });
  });

  it('should create comapny in Company and User Table and User isCompany is set to true', async () => {
    nock(process.env.NOTIFICATION_SERVICE_URL!)
      .post('/send-email')
      .reply(200, {});

    const res = await supertest(server).post('/api/v1/auth/signup').send({
      email,
      password,
      confirmPassword: password,
      companyName,
      rcNumber,
      address,
      phoneNumber,
    });

    const company = await Company.findOne({ email });
    const user = await User.findOne({ companyId: company!._id });
    expect(res.status).toEqual(201);
    expect(company).not.toBeNull();
    expect(user).not.toBeNull();
    expect(user!.isCompany).toBeTruthy();
    expect(user!.isActive).toBeFalsy();
  });
});
