import { DataSource } from 'typeorm';
import { Test, TestingModule } from '@nestjs/testing';
import { ConfigModule } from '@nestjs/config';
import { Task } from '../../../repositories/tasks/entity/task.entity';
import { AudioFile } from '../../../repositories/audio_files/entity/audio_file.entity';
import { CheckoutPermission } from '../../../repositories/checkout_permissions/entity/checkout_permission.entity';
import { UserGroup } from '../../../repositories/user_groups/entity/user_group.entity';
import { UserGroupMember } from '../../../repositories/user_groups/entity/user_group_member.entity';
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 {
  NotificationhubServiceMockValue,
  makeNotificationhubServiceMock,
} from './tasks.service.mock';

export const makeTaskTestingModuleWithNotificaiton = async (
  datasource: DataSource,
  notificationhubServiceMockValue: NotificationhubServiceMockValue,
): Promise<TestingModule | undefined> => {
  try {
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        ConfigModule.forRoot({
          envFilePath: ['.env.test', '.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(NotificationhubService)
      .useValue(makeNotificationhubServiceMock(notificationhubServiceMockValue))
      .compile();

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

export const createTask = async (
  datasource: DataSource,
  account_id: number,
  owner_user_id: number,
  author_id: string,
  work_type_id: string,
  priority: string,
  jobNumber: string,
  status: string,
  typist_user_id?: number | undefined,
  is_job_number_enabled?: boolean | undefined,
): Promise<{ taskId: number; audioFileId: number }> => {
  const { identifiers: audioFileIdentifiers } = await datasource
    .getRepository(AudioFile)
    .insert({
      account_id: account_id,
      owner_user_id: owner_user_id,
      url: '',
      file_name: 'x.zip',
      author_id: author_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: priority,
      audio_format: 'audio_format',
      is_encrypted: true,
    });
  const audioFile = audioFileIdentifiers.pop() as AudioFile;
  const { identifiers: taskIdentifiers } = await datasource
    .getRepository(Task)
    .insert({
      job_number: jobNumber,
      account_id: account_id,
      is_job_number_enabled: is_job_number_enabled ?? true,
      audio_file_id: audioFile.id,
      status: status,
      typist_user_id: typist_user_id,
      priority: priority,
      started_at: new Date().toISOString(),
      created_at: new Date(),
    });
  const task = taskIdentifiers.pop() as Task;
  return { taskId: task.id, audioFileId: audioFile.id };
};
/**
 *
 * @param datasource
 * @param task_id
 * @param user_id
 * @param user_group_id
 *
 */
export const createCheckoutPermissions = async (
  datasource: DataSource,
  task_id: number,
  user_id?: number,
  user_group_id?: number,
): Promise<void> => {
  await datasource.getRepository(CheckoutPermission).insert({
    task_id: task_id,
    user_id: user_id ?? null,
    user_group_id: user_group_id ?? null,
  });
};
/**
 *
 * @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 getTask = async (
  datasource: DataSource,
  task_id: number,
): Promise<Task | null> => {
  const task = await datasource.getRepository(Task).findOne({
    relations: {
      file: true,
    },
    where: {
      id: task_id,
    },
  });
  return task;
};

export const getCheckoutPermissions = async (
  datasource: DataSource,
  task_id: number,
): Promise<CheckoutPermission[]> => {
  const permissions = await datasource.getRepository(CheckoutPermission).find({
    where: {
      task_id: task_id,
    },
  });
  return permissions;
};
