import {
  BadRequestException,
  forwardRef,
  Inject,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { PaginationOptions } from '@docmost/db/pagination/pagination-options';
import { GroupService } from './group.service';
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
import { InjectKysely } from 'nestjs-kysely';
import { GroupUserRepo } from '@docmost/db/repos/group/group-user.repo';
import { SpaceMemberRepo } from '@docmost/db/repos/space/space-member.repo';
import { UserRepo } from '@docmost/db/repos/user/user.repo';
import { executeTx } from '@docmost/db/utils';
import { WatcherRepo } from '@docmost/db/repos/watcher/watcher.repo';
import { FavoriteRepo } from '@docmost/db/repos/favorite/favorite.repo';
import { AuditEvent, AuditResource } from '../../../common/events/audit-events';
import {
  AUDIT_SERVICE,
  IAuditService,
} from '../../../integrations/audit/audit.service';
import { dbOrTx } from '@docmost/db/utils';
import { WsService } from '../../../ws/ws.service';
import { PagePermissionRepo } from '@docmost/db/repos/page/page-permission.repo';
import { CollabAccessService } from '../../../collaboration/services/collab-access.service';

export type GroupAccess = { spaceIds: string[]; pageIds: string[] };

@Injectable()
export class GroupUserService {
  constructor(
    private groupUserRepo: GroupUserRepo,
    private spaceMemberRepo: SpaceMemberRepo,
    private userRepo: UserRepo,
    @Inject(forwardRef(() => GroupService))
    private groupService: GroupService,
    private readonly watcherRepo: WatcherRepo,
    private readonly favoriteRepo: FavoriteRepo,
    @InjectKysely() private readonly db: KyselyDB,
    @Inject(AUDIT_SERVICE) private readonly auditService: IAuditService,
    private readonly wsService: WsService,
    private readonly pagePermissionRepo: PagePermissionRepo,
    private readonly collabAccessService: CollabAccessService,
  ) {}

  async getGroupUsers(
    groupId: string,
    workspaceId: string,
    pagination: PaginationOptions,
    opts?: { adminView?: boolean },
  ) {
    await this.groupService.findAndValidateGroup(groupId, workspaceId);

    const groupUsers = await this.groupUserRepo.getGroupUsersPaginated(
      groupId,
      pagination,
      opts,
    );

    return groupUsers;
  }

  async addUsersToGroupBatch(
    userIds: string[],
    groupId: string,
    workspaceId: string,
    trx?: KyselyTransaction,
  ): Promise<void> {
    const db = dbOrTx(this.db, trx);
    await this.groupService.findAndValidateGroup(groupId, workspaceId, trx);

    if (userIds.length === 0) return;

    // make sure we have valid workspace users
    const validUsers = await db
      .selectFrom('users')
      .select(['id', 'name'])
      .where('users.id', 'in', userIds)
      .where('users.workspaceId', '=', workspaceId)
      .execute();

    if (validUsers.length === 0) return;

    // prepare users to add to group
    const groupUsersToInsert = [];
    for (const user of validUsers) {
      groupUsersToInsert.push({
        userId: user.id,
        groupId: groupId,
      });
    }

    // batch insert new group users
    await db
      .insertInto('groupUsers')
      .values(groupUsersToInsert)
      .onConflict((oc) => oc.columns(['userId', 'groupId']).doNothing())
      .execute();

    for (const user of validUsers) {
      this.auditService.log({
        event: AuditEvent.GROUP_MEMBER_ADDED,
        resourceType: AuditResource.GROUP,
        resourceId: groupId,
        changes: {
          after: {
            userId: user.id,
            userName: user.name,
          },
        },
      });
    }
  }

  async removeUserFromGroup(
    userId: string,
    groupId: string,
    workspaceId: string,
  ): Promise<void> {
    const group = await this.groupService.findAndValidateGroup(
      groupId,
      workspaceId,
    );

    const user = await this.userRepo.findById(userId, workspaceId);

    if (!user) {
      throw new NotFoundException('User not found');
    }

    if (group.isDefault) {
      throw new BadRequestException(
        'You cannot remove users from a default group',
      );
    }

    const groupUser = await this.groupUserRepo.getGroupUserById(
      userId,
      groupId,
    );

    if (!groupUser) {
      throw new BadRequestException('Group member not found');
    }

    const groupAccess = await this.getGroupAccess([groupId]);

    // TODO: use queue instead
    await executeTx(this.db, async (trx) => {
      await this.groupUserRepo.delete(userId, groupId, { trx });
      await this.removeWatchersAndFavoritesWithoutAccess(
        [userId],
        groupAccess.spaceIds,
        trx,
      );
    });

    await this.revokeRealtimeAccess([userId], groupAccess);

    this.auditService.log({
      event: AuditEvent.GROUP_MEMBER_REMOVED,
      resourceType: AuditResource.GROUP,
      resourceId: groupId,
      changes: {
        before: {
          userId: user.id,
          userName: user.name,
        },
      },
      metadata: {
        groupName: group.name,
      },
    });
  }

  // read before deleting a group, its page permissions cascade away with it
  async getGroupAccess(
    groupIds: string[],
    opts?: { trx?: KyselyTransaction },
  ): Promise<GroupAccess> {
    const spaceIds = await this.spaceMemberRepo.getSpaceIdsByGroupIds(
      groupIds,
      opts,
    );
    const pageIds = await this.pagePermissionRepo.getPageIdsByGroupIds(
      groupIds,
      opts,
    );
    return { spaceIds, pageIds };
  }

  async removeWatchersAndFavoritesWithoutAccess(
    userIds: string[],
    spaceIds: string[],
    trx: KyselyTransaction,
  ): Promise<void> {
    for (const spaceId of spaceIds) {
      await this.watcherRepo.deleteByUsersWithoutSpaceAccess(
        userIds,
        spaceId,
        { trx },
      );
      await this.favoriteRepo.deleteByUsersWithoutSpaceAccess(
        userIds,
        spaceId,
        { trx },
      );
    }
  }

  // call after commit, it never throws
  async revokeRealtimeAccess(
    userIds: string[],
    groupAccess: GroupAccess,
  ): Promise<void> {
    if (userIds.length === 0) return;
    if (!groupAccess.spaceIds.length && !groupAccess.pageIds.length) return;

    await this.collabAccessService.recheckAccess({ userIds });
    await this.wsService.removeUsersWithoutSpaceAccess(
      userIds,
      groupAccess.spaceIds,
    );
    await this.wsService.removeBaseSubscribersWithoutAccess(
      groupAccess.pageIds,
    );
  }
}
