import { Inject, Injectable, Logger } from '@nestjs/common';
import { IRedisService } from '../redis/redis.interface';

@Injectable()
export class UserSocialCleanupService {
  private readonly logger = new Logger(UserSocialCleanupService.name);
  private readonly FRIENDS_PREFIX = 'chat:friends:';
  private readonly FRIEND_DATA_PREFIX = 'chat:friend_data:';
  private readonly FRIEND_REQUESTS_PREFIX = 'chat:friend_requests:';
  private readonly FRIEND_REQUEST_DATA_PREFIX = 'chat:friend_request_data:';

  constructor(@Inject('REDIS_SERVICE') private readonly redisService: IRedisService) {}

  async clearUserSocialData(userId: string): Promise<void> {
    const normalizedUserId = userId.trim();
    if (!normalizedUserId) {
      return;
    }

    const [
      friendSetKeys,
      ownedFriendDataKeys,
      friendDataReferenceKeys,
      friendRequestSetKeys,
      ownedFriendRequestDataKeys,
      friendRequestDataReferenceKeys,
    ] = await Promise.all([
      this.redisService.keys(`${this.FRIENDS_PREFIX}*`),
      this.redisService.keys(`${this.FRIEND_DATA_PREFIX}${normalizedUserId}:*`),
      this.redisService.keys(`${this.FRIEND_DATA_PREFIX}*:${normalizedUserId}`),
      this.redisService.keys(`${this.FRIEND_REQUESTS_PREFIX}*`),
      this.redisService.keys(`${this.FRIEND_REQUEST_DATA_PREFIX}${normalizedUserId}:*`),
      this.redisService.keys(`${this.FRIEND_REQUEST_DATA_PREFIX}*:${normalizedUserId}`),
    ]);

    for (const friendSetKey of friendSetKeys) {
      if (friendSetKey !== `${this.FRIENDS_PREFIX}${normalizedUserId}`) {
        await this.redisService.srem(friendSetKey, normalizedUserId);
      }
    }

    for (const friendRequestSetKey of friendRequestSetKeys) {
      if (friendRequestSetKey !== `${this.FRIEND_REQUESTS_PREFIX}${normalizedUserId}`) {
        await this.redisService.srem(friendRequestSetKey, normalizedUserId);
      }
    }

    const keysToDelete = new Set([
      `${this.FRIENDS_PREFIX}${normalizedUserId}`,
      `${this.FRIEND_REQUESTS_PREFIX}${normalizedUserId}`,
      ...ownedFriendDataKeys,
      ...friendDataReferenceKeys,
      ...ownedFriendRequestDataKeys,
      ...friendRequestDataReferenceKeys,
    ]);

    for (const key of keysToDelete) {
      await this.redisService.del(key);
    }

    this.logger.log('已清理用户好友缓存', {
      userId: normalizedUserId,
      deletedKeys: keysToDelete.size,
    });
  }
}
