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 { Task } from '../../../repositories/tasks/entity/task.entity';
import { AudioFile } from '../../../repositories/audio_files/entity/audio_file.entity';
import { BlobstorageService } from '../../../gateways/blobstorage/blobstorage.service';
import {
  BlobstorageServiceMockValue,
  makeBlobstorageServiceMock,
} from './files.service.mock';
import { User } from '../../../repositories/users/entity/user.entity';
import { Account } from '../../../repositories/accounts/entity/account.entity';
import { TemplateFile } from '../../../repositories/template_files/entity/template_file.entity';

export const createAccount = async (
  datasource: DataSource,
): Promise<{ accountId: number }> => {
  const { identifiers } = await datasource.getRepository(Account).insert({
    tier: 5,
    country: 'US',
    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,
): Promise<{ userId: number; externalId: string; authorId: 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: true,
    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, authorId: author_id };
};

export const createTask = async (
  datasource: DataSource,
  account_id: number,
  url: string,
  fileName: string,
  status: string,
  typist_user_id?: number | undefined,
  author_id?: string | undefined,
): Promise<{ audioFileId: number }> => {
  const { identifiers: audioFileIdentifiers } = await datasource
    .getRepository(AudioFile)
    .insert({
      account_id: account_id,
      owner_user_id: 1,
      url: url,
      file_name: fileName,
      author_id: author_id ?? 'DEFAULT_ID',
      work_type_id: 'work_type_id',
      started_at: new Date(),
      duration: '100000',
      finished_at: new Date(),
      uploaded_at: new Date(),
      file_size: 10000,
      priority: '00',
      audio_format: 'audio_format',
      is_encrypted: true,
    });
  const audioFile = audioFileIdentifiers.pop() as AudioFile;
  const { identifiers: templateFileIdentifiers } = await datasource
    .getRepository(TemplateFile)
    .insert({
      account_id: account_id,
      url: url,
      file_name: fileName,
      created_by: 'test_runner',
      created_at: new Date(),
      updated_by: 'updater',
      updated_at: new Date(),
    });

  const templateFile = templateFileIdentifiers.pop() as TemplateFile;
  await datasource.getRepository(Task).insert({
    job_number: '00000001',
    account_id: account_id,
    is_job_number_enabled: true,
    audio_file_id: audioFile.id,
    template_file_id: templateFile.id,
    typist_user_id: typist_user_id,
    status: status,
    priority: '01',
    started_at: new Date().toISOString(),
    created_at: new Date(),
  });

  return { audioFileId: audioFile.id };
};

export const makeTestingModuleWithBlob = async (
  datasource: DataSource,
  blobStorageService: BlobstorageServiceMockValue,
): 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(BlobstorageService)
      .useValue(makeBlobstorageServiceMock(blobStorageService))
      .compile();

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