import { Injectable } from '@nestjs/common';
import { DataSource, In, IsNull } from 'typeorm';
import { UserGroup } from './entity/user_group.entity';
import { UserGroupMember } from './entity/user_group_member.entity';

@Injectable()
export class UserGroupsRepositoryService {
  constructor(private dataSource: DataSource) {}

  async getUserGroups(account_id: number): Promise<UserGroup[]> {
    const value = await this.dataSource.transaction(async (entityManager) => {
      const userGroupRepo = entityManager.getRepository(UserGroup);

      const userGroups = await userGroupRepo.find({
        // 論理削除されていないレコードを取得
        where: { account_id: account_id, deleted_at: IsNull() },
      });

      return userGroups;
    });
    return value;
  }
  /**
   * ユーザーグループIDからユーザー所属一覧を取得する
   * @param groupIds
   * @returns users from groups
   */
  async getGroupMembersFromGroupIds(
    groupIds: number[],
  ): Promise<UserGroupMember[]> {
    return await this.dataSource.transaction(async (entityManager) => {
      const groupMemberRepo = entityManager.getRepository(UserGroupMember);

      const groupMembers = await groupMemberRepo.find({
        relations: {
          user: true,
        },
        where: {
          user_group_id: In(groupIds),
        },
      });

      return groupMembers;
    });
  }
}
