import { Test, TestingModule } from '@nestjs/testing';
import { AdB2cService } from '../../../gateways/adb2c/adb2c.service';
import { JwkSignKey, B2cMetadata } from '../../../common/token';
import { AuthService } from '../auth.service';
import { ConfigService } from '@nestjs/config';
import { UsersRepositoryService } from '../../../repositories/users/users.repository.service';

export type AdB2cMockValue = {
  getMetaData: B2cMetadata | Error;
  getSignKeySets: JwkSignKey[] | Error;
};

export const makeAuthServiceMock = async (
  adB2cMockValue: AdB2cMockValue,
): Promise<AuthService> => {
  const module: TestingModule = await Test.createTestingModule({
    providers: [AuthService],
  })
    .useMocker((token) => {
      switch (token) {
        case AdB2cService:
          return makeAdB2cServiceMock(adB2cMockValue);
        case ConfigService:
          return {};
        case UsersRepositoryService:
          return {};
      }
    })
    .compile();

  return module.get<AuthService>(AuthService);
};

export const makeDefaultAdB2cMockValue = (): AdB2cMockValue => {
  return {
    getMetaData: {
      issuer: 'issuer',
    },
    getSignKeySets: [
      {
        kid: 'kid',
        nbf: 1111111111,
        use: 'sig',
        kty: 'RSA',
        e: 'e',
        n: 'n',
      },
    ],
  };
};

export const makeAdB2cServiceMock = (value: AdB2cMockValue) => {
  const { getMetaData, getSignKeySets } = value;

  return {
    getMetaData:
      getMetaData instanceof Error
        ? jest.fn<Promise<void>, []>().mockRejectedValue(getMetaData)
        : jest.fn<Promise<B2cMetadata>, []>().mockResolvedValue(getMetaData),
    getSignKeySets:
      getSignKeySets instanceof Error
        ? jest.fn<Promise<void>, []>().mockRejectedValue(getSignKeySets)
        : jest
            .fn<Promise<JwkSignKey[]>, []>()
            .mockResolvedValue(getSignKeySets),
  };
};

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export const makeDefaultGetPublicKeyFromJwk = (jwkKey: JwkSignKey): string => {
  return [
    '-----BEGIN PUBLIC KEY-----',
    'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5IZZNgDew9eGmuFTezwd',
    'HYLSaJvUPPIKYoiOeVLD1paWNI517Vkaoh0ngprcKOdv6T1N07V4igK7mOim2zY3',
    'yCTR6wcWR3PfFJrl9vh5SOo79koZoJb27YiM4jtxfx2dezzp0T2GoNR5rRolPUbW',
    'FJXnDe0DVXYXpJLb4LAlF2XAyYX0SYKUVUsJnzm5k4xbXtnwPwVbpm0EdswBE6qS',
    'fiL9zWk9dvHoKzSnfSDzDFoFcEoVchawzYXf/MM1YR4wo5XyzECc6Q5Ah4z522//',
    'mBNNaDHv83Yuw3mGShT73iJ0JQdkTturshv2Ecma38r6ftrIwNYXw4VVatJM8+GO',
    'OQIDAQAB',
    '-----END PUBLIC KEY-----',
  ].join('\n');
};
