import { HttpException, HttpStatus } from '@nestjs/common';
import {
  makeNotificationServiceMock,
  makeDefaultNotificationHubMockValue,
  makeDefaultUsersRepositoryMockValue,
} from './test/notification.service.mock';
import { makeErrorResponse } from '../../common/error/makeErrorResponse';
import { makeContext } from '../../common/log';

describe('NotificationService.register', () => {
  it('ユーザーから渡されたPNSハンドルをNotificationHubに登録できる', async () => {
    const notificationHubMockValue = makeDefaultNotificationHubMockValue();
    const usersRepositoryMockValue = makeDefaultUsersRepositoryMockValue();

    const service = await makeNotificationServiceMock(
      usersRepositoryMockValue,
      notificationHubMockValue,
    );

    expect(
      await service.register(
        makeContext('trackingId'),
        'external_id',
        'apns',
        'handler',
      ),
    ).toEqual(undefined);
  });
  it('DBからのユーザー取得に失敗した場合、エラーとなる', async () => {
    const notificationHubMockValue = makeDefaultNotificationHubMockValue();
    const usersRepositoryMockValue = makeDefaultUsersRepositoryMockValue();
    usersRepositoryMockValue.findUserByExternalId = new Error('DB failed.');

    const service = await makeNotificationServiceMock(
      usersRepositoryMockValue,
      notificationHubMockValue,
    );

    await expect(
      service.register(
        makeContext('trackingId'),
        'external_id',
        'apns',
        'handler',
      ),
    ).rejects.toEqual(
      new HttpException(
        makeErrorResponse('E009999'),
        HttpStatus.INTERNAL_SERVER_ERROR,
      ),
    );
  });

  it('NotificationHubへの登録に失敗した場合、エラーとなる', async () => {
    const notificationHubMockValue = makeDefaultNotificationHubMockValue();
    const usersRepositoryMockValue = makeDefaultUsersRepositoryMockValue();
    notificationHubMockValue.register = new Error('register failed.');

    const service = await makeNotificationServiceMock(
      usersRepositoryMockValue,
      notificationHubMockValue,
    );

    await expect(
      service.register(
        makeContext('trackingId'),
        'external_id',
        'apns',
        'handler',
      ),
    ).rejects.toEqual(
      new HttpException(
        makeErrorResponse('E009999'),
        HttpStatus.INTERNAL_SERVER_ERROR,
      ),
    );
  });
});
