import { DataSource } from 'typeorm';
import { Test, TestingModule } from '@nestjs/testing';
import { ConfigModule } from '@nestjs/config';
import { UserGroupsRepositoryModule } from '../../../repositories/user_groups/user_groups.repository.module';
import { TasksRepositoryModule } from '../../../repositories/tasks/tasks.repository.module';
import { AuthModule } from '../../../features/auth/auth.module';
import { AdB2cModule } from '../../../gateways/adb2c/adb2c.module';
import { AccountsModule } from '../../../features/accounts/accounts.module';
import { UsersModule } from '../../../features/users/users.module';
import { FilesModule } from '../../../features/files/files.module';
import { TasksModule } from '../../../features/tasks/tasks.module';
import { SendGridModule } from '../../../features/../gateways/sendgrid/sendgrid.module';
import { LicensesModule } from '../../../features/licenses/licenses.module';
import { AccountsRepositoryModule } from '../../../repositories/accounts/accounts.repository.module';
import { UsersRepositoryModule } from '../../../repositories/users/users.repository.module';
import { LicensesRepositoryModule } from '../../../repositories/licenses/licenses.repository.module';
import { AudioFilesRepositoryModule } from '../../../repositories/audio_files/audio_files.repository.module';
import { AudioOptionItemsRepositoryModule } from '../../../repositories/audio_option_items/audio_option_items.repository.module';
import { CheckoutPermissionsRepositoryModule } from '../../../repositories/checkout_permissions/checkout_permissions.repository.module';
import { NotificationModule } from '../../../features//notification/notification.module';
import { NotificationhubModule } from '../../../gateways/notificationhub/notificationhub.module';
import { BlobstorageModule } from '../../../gateways/blobstorage/blobstorage.module';
import { AuthGuardsModule } from '../../../common/guards/auth/authguards.module';
import { SortCriteriaRepositoryModule } from '../../../repositories/sort_criteria/sort_criteria.repository.module';
import { AuthService } from '../../../features/auth/auth.service';
import { AccountsService } from '../../../features/accounts/accounts.service';
import { UsersService } from '../../../features/users/users.service';
import { NotificationhubService } from '../../../gateways/notificationhub/notificationhub.service';
import { FilesService } from '../../../features/files/files.service';
import { LicensesService } from '../../../features/licenses/licenses.service';
import { TasksService } from '../../../features/tasks/tasks.service';
import { User } from '../../../repositories/users/entity/user.entity';
import { Account } from '../../../repositories/accounts/entity/account.entity';
import { UserGroup } from '../../../repositories/user_groups/entity/user_group.entity';
import { UserGroupMember } from '../../../repositories/user_groups/entity/user_group_member.entity';
import { License } from '../../../repositories/licenses/entity/license.entity';
import { AdB2cMockValue, makeAdB2cServiceMock } from './users.service.mock';
import { AdB2cService } from '../../../gateways/adb2c/adb2c.service';
import { LICENSE_ALLOCATED_STATUS, LICENSE_TYPE } from '../../../constants';

export const createAccount = async (
  datasource: DataSource,
): Promise<{ accountId: number }> => {
  const { identifiers } = await datasource.getRepository(Account).insert({
    tier: 1,
    country: 'JP',
    delegation_permission: false,
    locked: false,
    company_name: 'test inc.',
    verified: true,
    deleted_at: '',
    created_by: 'test_runner',
    created_at: new Date(),
    updated_by: 'updater',
    updated_at: new Date(),
  });
  const account = identifiers.pop() as Account;
  return { accountId: account.id };
};

export const createUser = async (
  datasource: DataSource,
  accountId: number,
  external_id: string,
  role: string,
  author_id?: string | undefined,
  auto_renew?: boolean,
): Promise<{ userId: number; externalId: string }> => {
  const { identifiers } = await datasource.getRepository(User).insert({
    account_id: accountId,
    external_id: external_id,
    role: role,
    accepted_terms_version: '1.0',
    author_id: author_id,
    email_verified: true,
    auto_renew: auto_renew,
    license_alert: true,
    notification: true,
    encryption: false,
    prompt: false,
    created_by: 'test_runner',
    created_at: new Date(),
    updated_by: 'updater',
    updated_at: new Date(),
  });
  const user = identifiers.pop() as User;
  return { userId: user.id, externalId: external_id };
};

/**
 *
 * @param datasource
 * @param account_id
 * @param user_group_name
 * @param user_id
 * @returns
 */
export const createUserGroup = async (
  datasource: DataSource,
  account_id: number,
  user_group_name: string,
  user_id: number[],
): Promise<{ userGroupId: number }> => {
  const { identifiers: userGroupIdentifiers } = await datasource
    .getRepository(UserGroup)
    .insert({
      account_id: account_id,
      name: user_group_name,
      created_by: 'test',
      updated_by: 'test',
    });
  const userGroup = userGroupIdentifiers.pop() as UserGroup;
  const userGroupMenber = user_id.map((id) => {
    return {
      user_group_id: userGroup.id,
      user_id: id,
      created_by: 'test',
      updated_by: 'test',
    };
  });
  await datasource.getRepository(UserGroupMember).save(userGroupMenber);

  return { userGroupId: userGroup.id };
};

export const createLicense = async (
  datasource: DataSource,
  accountId: number,
  userId?: number,
  expiry_date?: Date,
): Promise<void> => {
  const { identifiers } = await datasource.getRepository(License).insert({
    account_id: accountId,
    type: LICENSE_TYPE.NORMAL,
    status: LICENSE_ALLOCATED_STATUS.ALLOCATED,
    allocated_user_id: userId,
    expiry_date: expiry_date,
    created_by: 'test_runner',
    created_at: new Date(),
    updated_by: 'updater',
    updated_at: new Date(),
  });
  identifiers.pop() as License;
};

export const makeTestingModuleWithAdb2c = async (
  datasource: DataSource,
  adB2cMockValue: AdB2cMockValue,
): Promise<TestingModule> => {
  try {
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        ConfigModule.forRoot({
          envFilePath: ['.env.local', '.env'],
          isGlobal: true,
        }),
        AuthModule,
        AdB2cModule,
        AccountsModule,
        UsersModule,
        FilesModule,
        TasksModule,
        UsersModule,
        SendGridModule,
        LicensesModule,
        AccountsRepositoryModule,
        UsersRepositoryModule,
        LicensesRepositoryModule,
        AudioFilesRepositoryModule,
        AudioOptionItemsRepositoryModule,
        TasksRepositoryModule,
        CheckoutPermissionsRepositoryModule,
        UserGroupsRepositoryModule,
        UserGroupsRepositoryModule,
        NotificationModule,
        NotificationhubModule,
        BlobstorageModule,
        AuthGuardsModule,
        SortCriteriaRepositoryModule,
      ],
      providers: [
        AuthService,
        AccountsService,
        UsersService,
        NotificationhubService,
        FilesService,
        TasksService,
        LicensesService,
      ],
    })
      .useMocker(async (token) => {
        switch (token) {
          case DataSource:
            return datasource;
        }
      })
      .overrideProvider(AdB2cService)
      .useValue(makeAdB2cServiceMock(adB2cMockValue))
      .compile();

    return module;
  } catch (e) {
    console.log(e);
  }
};
