import {
  BadRequestException,
  ForbiddenException,
  NotFoundException,
} from '@nestjs/common';
import { Types } from 'mongoose';
import { ExperienceLevel } from '../../common/enums/experience-level.enum';
import { MusicRole } from '../../common/enums/music-role.enum';
import { UserRole } from '../../common/enums/user-role.enum';
import { UsersService } from './users.service';

type MockMap = Record<string, jest.Mock>;

const createHarness = (options: {
  repository?: Partial<MockMap>;
  connection?: { collection: jest.Mock };
  storage?: Partial<MockMap>;
} = {}) => {
  const userId = new Types.ObjectId().toString();
  const baseUser: Record<string, any> = {
    id: userId,
    _id: new Types.ObjectId(userId),
    name: 'Artist',
    username: 'artist',
    email: 'artist@example.com',
    role: UserRole.USER,
    avatar: 'uploads/users/avatar/old.jpg',
    coverImage: 'uploads/users/cover/old.jpg',
    isDisabled: false,
    isPrivate: false,
    isOnline: false,
    get(field: string) {
      return this[field];
    },
    toObject() {
      return { ...this, get: undefined, toObject: undefined };
    },
  };
  const repository: MockMap = {
    findOne: jest.fn().mockResolvedValue(null),
    findOneWithPassword: jest.fn().mockResolvedValue(null),
    create: jest.fn().mockImplementation((payload) => Promise.resolve({ ...baseUser, ...payload })),
    findById: jest.fn().mockResolvedValue(baseUser),
    findByIdWithPassword: jest.fn().mockResolvedValue(baseUser),
    updateById: jest.fn().mockImplementation((_id, payload) =>
      Promise.resolve({ ...baseUser, ...payload }),
    ),
    deleteById: jest.fn().mockResolvedValue(baseUser),
    setPresence: jest.fn().mockResolvedValue(undefined),
    findMany: jest.fn().mockResolvedValue([]),
    count: jest.fn().mockResolvedValue(0),
    ...options.repository,
  };
  const follows = { countDocuments: jest.fn().mockResolvedValue(0) };
  const connection = options.connection ?? {
    collection: jest.fn((name: string) => {
      if (name === 'follows') return follows;
      throw new Error(`Unexpected collection ${name}`);
    }),
  };
  const audit = { logSuperAdminAction: jest.fn().mockResolvedValue(undefined) };
  const storage: MockMap = {
    saveFile: jest.fn().mockImplementation(({ folderSegments, extension }) =>
      Promise.resolve(`uploads/${folderSegments.join('/')}/saved${extension}`),
    ),
    deleteFile: jest.fn().mockResolvedValue(undefined),
    ...options.storage,
  };
  const config = {
    get: jest.fn((key: string) =>
      key === 'security.bcryptSaltRounds' ? 4 : undefined,
    ),
  };
  const feedVersionService = {
    bumpGlobalVersion: jest.fn().mockResolvedValue(1),
    bumpUserVersion: jest.fn().mockResolvedValue(1),
  };
  const service = new UsersService(
    connection as any,
    repository as any,
    audit as any,
    config as any,
    storage as any,
    feedVersionService as any,
  );
  return {
    service,
    repository,
    connection,
    follows,
    audit,
    storage,
    feedVersionService,
    baseUser,
    userId,
  };
};

const image = (name = 'avatar.jpg') => ({
  originalname: name,
  mimetype: 'image/jpeg',
  size: 3,
  buffer: Buffer.from([0xff, 0xd8, 0xff]),
});

describe('UsersService security and consistency', () => {
  describe('account creation', () => {
    it('normalizes identity fields and sets secure defaults', async () => {
      const { service, repository } = createHarness();

      await service.create({
        name: 'Artist',
        email: 'ARTIST@EXAMPLE.COM',
        username: 'ARTIST',
        password: 'already-hashed',
      } as any);

      expect(repository.findOne).toHaveBeenCalledWith({
        $or: [{ email: 'artist@example.com' }, { username: 'artist' }],
      });
      expect(repository.create).toHaveBeenCalledWith(
        expect.objectContaining({
          email: 'artist@example.com',
          username: 'artist',
          role: UserRole.USER,
          isPrivate: false,
          isDisabled: false,
          authProvider: 'local',
          experienceLevel: ExperienceLevel.BEGINNER,
          musicRoles: [],
        }),
      );
    });

    it('rejects duplicate email or username before write', async () => {
      const { service, repository } = createHarness({
        repository: { findOne: jest.fn().mockResolvedValue({ id: 'existing' }) },
      });

      await expect(
        service.create({
          name: 'Artist',
          email: 'artist@example.com',
          username: 'artist',
          password: 'hash',
        } as any),
      ).rejects.toBeInstanceOf(BadRequestException);
      expect(repository.create).not.toHaveBeenCalled();
    });

    it('deletes a newly uploaded avatar if account creation fails', async () => {
      const { service, storage } = createHarness({
        repository: { create: jest.fn().mockRejectedValue(new Error('write failed')) },
      });

      await expect(
        service.createWithOptionalAvatarFile(
          {
            name: 'Artist',
            email: 'artist@example.com',
            username: 'artist',
            password: 'hash',
          } as any,
          image(),
        ),
      ).rejects.toThrow('write failed');
      expect(storage.deleteFile).toHaveBeenCalledWith('uploads/users/avatar/saved.jpg');
    });

    it('rolls back both the database record and managed avatar', async () => {
      const { service, repository, storage } = createHarness();

      await service.rollbackSignupCreatedUser('user-1', 'uploads/avatar.jpg');

      expect(repository.deleteById).toHaveBeenCalledWith('user-1');
      expect(storage.deleteFile).toHaveBeenCalledWith('uploads/avatar.jpg');
    });

    it('requires matching admin passwords and audits successful creation', async () => {
      const mismatch = createHarness();
      await expect(
        mismatch.service.createAdminBySuperAdmin('root', {
          name: 'Admin',
          username: 'admin',
          email: 'admin@example.com',
          password: 'StrongPass123!',
          confirmPassword: 'OtherPass123!',
        }),
      ).rejects.toBeInstanceOf(BadRequestException);

      const valid = createHarness();
      const admin = await valid.service.createAdminBySuperAdmin('root', {
        name: 'Admin',
        username: 'admin',
        email: 'admin@example.com',
        password: 'StrongPass123!',
        confirmPassword: 'StrongPass123!',
      });
      expect(admin.role).toBe(UserRole.ADMIN);
      expect(valid.audit.logSuperAdminAction).toHaveBeenCalledWith(
        'root',
        'admin_create',
        'user',
        valid.userId,
        { role: UserRole.ADMIN },
      );
    });
  });

  describe('authorization and managed updates', () => {
    it('prevents assigning or managing a superadmin through ordinary APIs', async () => {
      const assignment = createHarness();
      await expect(
        assignment.service.updateUserRoleBySuperAdmin('root', assignment.userId, {
          role: UserRole.SUPERADMIN,
        }),
      ).rejects.toBeInstanceOf(BadRequestException);

      const protectedUser = createHarness({
        repository: {
          findById: jest.fn().mockResolvedValue({ role: UserRole.SUPERADMIN }),
        },
      });
      await expect(
        protectedUser.service.disableUserBySuperAdmin('root', protectedUser.userId, {}),
      ).rejects.toBeInstanceOf(ForbiddenException);
      expect(protectedUser.repository.updateById).not.toHaveBeenCalled();
    });

    it('updates allowed roles and records an audit event', async () => {
      const { service, repository, audit, userId } = createHarness();

      const result = await service.updateUserRoleBySuperAdmin('root', userId, {
        role: UserRole.ADMIN,
      });

      expect(result.role).toBe(UserRole.ADMIN);
      expect(repository.updateById).toHaveBeenCalledWith(userId, { role: UserRole.ADMIN });
      expect(audit.logSuperAdminAction).toHaveBeenCalledWith(
        'root',
        'user_role_update',
        'user',
        userId,
        { role: UserRole.ADMIN },
      );
    });

    it('normalizes managed email/username and rejects cross-account duplicates', async () => {
      const { service, repository, userId } = createHarness();
      await service.updateUserBySuperAdmin('root', userId, {
        email: ' NEW@EXAMPLE.COM ',
        username: ' NEW_NAME ',
      });
      expect(repository.updateById).toHaveBeenCalledWith(
        userId,
        expect.objectContaining({ email: 'new@example.com', username: 'new_name' }),
      );

      const duplicate = createHarness({
        repository: {
          findOne: jest.fn().mockResolvedValue({ id: 'different-user' }),
        },
      });
      await expect(
        duplicate.service.updateUserBySuperAdmin('root', duplicate.userId, {
          email: 'taken@example.com',
        }),
      ).rejects.toBeInstanceOf(BadRequestException);
    });

    it('rejects empty managed identity fields', async () => {
      for (const dto of [{ email: ' ' }, { username: ' ' }]) {
        const { service, userId } = createHarness();
        await expect(service.updateUserBySuperAdmin('root', userId, dto)).rejects.toBeInstanceOf(
          BadRequestException,
        );
      }
    });

    it('fails closed when a repository update loses the target', async () => {
      const { service, userId } = createHarness({
        repository: { updateById: jest.fn().mockResolvedValue(null) },
      });

      await expect(
        service.updateUserRoleBySuperAdmin('root', userId, { role: UserRole.ADMIN }),
      ).rejects.toBeInstanceOf(NotFoundException);
    });

    it('disables and enables users with complete audit metadata', async () => {
      const { service, repository, audit, userId } = createHarness();

      await service.disableUserBySuperAdmin('root', userId, { reason: 'abuse' });
      expect(repository.updateById).toHaveBeenCalledWith(
        userId,
        expect.objectContaining({
          isDisabled: true,
          disabledReason: 'abuse',
          disabledBy: 'root',
          disabledAt: expect.any(Date),
        }),
      );

      await service.enableUserBySuperAdmin('root', userId);
      expect(repository.updateById).toHaveBeenCalledWith(userId, {
        isDisabled: false,
        disabledAt: null,
        disabledReason: '',
        disabledBy: null,
      });
      expect(audit.logSuperAdminAction).toHaveBeenCalledWith(
        'root',
        'user_enable',
        'user',
        userId,
      );
    });
  });

  describe('public identity, presence and profile files', () => {
    it('maps missing and disabled users to the same public not-found result', async () => {
      const missing = createHarness({
        repository: { findById: jest.fn().mockResolvedValue(null) },
      });
      await expect(missing.service.findByIdOrFail(missing.userId)).rejects.toBeInstanceOf(
        NotFoundException,
      );

      const disabled = createHarness({
        repository: { findById: jest.fn().mockResolvedValue({ isDisabled: true }) },
      });
      await expect(disabled.service.findPublicByIdOrFail(disabled.userId)).rejects.toBeInstanceOf(
        NotFoundException,
      );
    });

    it('does not query follows for own profile and resolves other-profile state', async () => {
      const own = createHarness();
      await expect(own.service.findPublicByIdForViewer(own.userId, own.userId)).resolves.toMatchObject({
        isFollowing: false,
        following: false,
        isOwnProfile: true,
      });
      expect(own.follows.countDocuments).not.toHaveBeenCalled();

      const viewerId = new Types.ObjectId().toString();
      const other = createHarness();
      other.follows.countDocuments.mockResolvedValue(1);
      await expect(
        other.service.findPublicByIdForViewer(other.userId, viewerId),
      ).resolves.toMatchObject({ isFollowing: true, following: true, isOwnProfile: false });
    });

    it('ignores invalid presence IDs and updates valid IDs', async () => {
      const { service, repository, userId } = createHarness();
      await service.setPresence('not-an-object-id', true);
      expect(repository.setPresence).not.toHaveBeenCalled();

      await service.setPresence(userId, true);
      expect(repository.setPresence).toHaveBeenCalledWith(userId, true, expect.any(Date));
    });

    it('normalizes email/username lookups', async () => {
      const { service, repository } = createHarness();
      await service.findByEmail('ARTIST@EXAMPLE.COM');
      await service.findByEmailWithPassword('ARTIST@EXAMPLE.COM');
      await service.findByUsername('ARTIST');
      await service.findByGoogleId('google-1');

      expect(repository.findOne).toHaveBeenCalledWith({ email: 'artist@example.com' });
      expect(repository.findOne).toHaveBeenCalledWith({ username: 'artist' });
      expect(repository.findOne).toHaveBeenCalledWith({ googleId: 'google-1' });
    });

    it('requires finite coordinates during profile setup', async () => {
      const { service, userId } = createHarness();
      await expect(
        service.updateProfileSetup(userId, { latitude: Number.NaN, longitude: 10 } as any),
      ).rejects.toBeInstanceOf(BadRequestException);
    });

    it('saves new profile images and deletes replaced managed files', async () => {
      const { service, storage, repository, userId } = createHarness();
      await service.updateProfile(userId, { bio: 'new bio' }, image('avatar.jpg'), image('cover.jpg'));

      expect(repository.updateById).toHaveBeenCalledWith(
        userId,
        expect.objectContaining({
          avatar: 'uploads/users/avatar/saved.jpg',
          coverImage: 'uploads/users/cover/saved.jpg',
        }),
      );
      expect(storage.deleteFile).toHaveBeenCalledWith('uploads/users/avatar/old.jpg');
      expect(storage.deleteFile).toHaveBeenCalledWith('uploads/users/cover/old.jpg');
    });

    it('invalidates global and user feeds when a public account becomes private', async () => {
      const { service, feedVersionService, userId } = createHarness();

      await service.updateProfile(userId, { isPrivate: true });

      expect(feedVersionService.bumpGlobalVersion).toHaveBeenCalled();
      expect(feedVersionService.bumpUserVersion).toHaveBeenCalledWith(userId);
    });

    it('cleans newly uploaded files if profile update loses its user', async () => {
      const { service, storage, userId } = createHarness({
        repository: { updateById: jest.fn().mockResolvedValue(null) },
      });

      await expect(service.updateProfile(userId, {}, image())).rejects.toBeInstanceOf(
        NotFoundException,
      );
      expect(storage.deleteFile).toHaveBeenCalledWith('uploads/users/avatar/saved.jpg');
    });

    it('rejects spoofed or oversized profile media before storage', async () => {
      const { service, storage, userId } = createHarness();

      await expect(
        service.updateProfile(userId, {}, {
          originalname: 'avatar.exe',
          mimetype: 'application/octet-stream',
          size: 3,
          buffer: Buffer.from('bad'),
        }),
      ).rejects.toBeInstanceOf(BadRequestException);
      expect(storage.saveFile).not.toHaveBeenCalled();
    });

    it('throws when password/email verification target vanished', async () => {
      for (const method of ['updatePassword', 'markEmailVerified'] as const) {
        const { service, userId } = createHarness({
          repository: { updateById: jest.fn().mockResolvedValue(null) },
        });
        const promise =
          method === 'updatePassword'
            ? service.updatePassword(userId, 'hash')
            : service.markEmailVerified(userId);
        await expect(promise).rejects.toBeInstanceOf(NotFoundException);
      }
    });
  });

  describe('search safety and pagination', () => {
    it('escapes public search regex and combines every supported filter', async () => {
      const { service, repository } = createHarness({
        repository: {
          findMany: jest.fn().mockResolvedValue([{ id: 'user-1' }]),
          count: jest.fn().mockResolvedValue(1),
        },
      });

      const result = await service.searchUsers({
        page: 2,
        limit: 5,
        q: 'a.*(b)',
        isVerified: true,
        musicRole: MusicRole.SINGER,
        experienceLevel: ExperienceLevel.PROFESSIONAL,
        isPrivate: false,
        hasAvatar: true,
        sortBy: 'followersCount',
        sortOrder: 'asc' as any,
      });

      expect(result).toMatchObject({ page: 2, limit: 5, total: 1, totalPages: 1 });
      const filter = repository.findMany.mock.calls[0][0];
      expect(filter.$and[1].$or[0].name.$regex).toBe('a\\.\\*\\(b\\)');
      expect(filter.$and).toEqual(
        expect.arrayContaining([
          { isDisabled: false },
          { isVerified: true },
          { musicRoles: MusicRole.SINGER },
          { experienceLevel: ExperienceLevel.PROFESSIONAL },
          { isPrivate: false },
          { avatar: { $ne: '' } },
        ]),
      );
      expect(repository.findMany).toHaveBeenCalledWith(filter, 5, 5, {
        followersCount: 1,
      });
    });

    it('supports avatar-absent filters and superadmin searches without exposing superadmins', async () => {
      const { service, repository } = createHarness();
      await service.searchUsers({ hasAvatar: false });
      const publicFilter = repository.findMany.mock.calls[0][0];
      expect(publicFilter.$and).toContainEqual({
        $or: [{ avatar: '' }, { avatar: { $exists: false } }],
      });

      await service.searchUsersForSuperAdmin({ q: 'root', hasAvatar: false });
      const adminFilter = repository.findMany.mock.calls[1][0];
      expect(adminFilter.$and).toContainEqual({ role: { $ne: UserRole.SUPERADMIN } });
    });

    it('discovers public talents and can skip expensive role buckets', async () => {
      const { service, repository } = createHarness();
      const result = await service.discoverTalents({
        includeRoleBuckets: false,
        hasAvatarOnly: false,
        musicRole: MusicRole.COMPOSER,
      });

      expect(result.roleBuckets).toEqual([]);
      expect(result.activeRole).toBe(MusicRole.COMPOSER);
      const filter = repository.findMany.mock.calls[0][0];
      expect(filter.$and).toEqual(
        expect.arrayContaining([
          { isDisabled: false },
          { role: UserRole.USER },
          { isPrivate: false },
          { musicRoles: { $exists: true, $ne: [] } },
        ]),
      );
    });

    it('builds a count bucket for every music role when requested', async () => {
      const { service, repository } = createHarness({
        repository: { count: jest.fn().mockResolvedValue(2) },
      });

      const result = await service.discoverTalents({ includeRoleBuckets: true });

      expect(result.roleBuckets).toHaveLength(Object.values(MusicRole).length);
      expect(repository.count).toHaveBeenCalledTimes(Object.values(MusicRole).length + 1);
    });

    it('lists admins with escaped query, verification filter and stable pagination', async () => {
      const { service, repository } = createHarness({
        repository: { count: jest.fn().mockResolvedValue(21) },
      });

      const result = await service.listAdminsBySuperAdmin({
        page: 2,
        limit: 10,
        q: 'a+b',
        isVerified: false,
      });

      expect(result).toMatchObject({ page: 2, limit: 10, total: 21, totalPages: 3 });
      const [filter, skip, limit] = repository.findMany.mock.calls[0];
      expect(filter).toMatchObject({ role: UserRole.ADMIN, isVerified: false });
      expect(filter.$or[0].name.$regex).toBe('a\\+b');
      expect([skip, limit]).toEqual([10, 10]);
    });
  });

  describe('admin orchestration and remaining public helpers', () => {
    it('requires an admin target for admin-only update and delete operations', async () => {
      const nonAdmin = createHarness();
      await expect(
        nonAdmin.service.updateAdminBySuperAdmin('root', nonAdmin.userId, { name: 'Changed' }),
      ).rejects.toBeInstanceOf(BadRequestException);

      const admin = createHarness({
        repository: {
          findById: jest.fn().mockResolvedValue({
            ...nonAdmin.baseUser,
            role: UserRole.ADMIN,
          }),
        },
      });
      (admin.service as any).deleteUserRelatedData = jest.fn().mockResolvedValue(undefined);
      await admin.service.deleteAdminBySuperAdmin('root', admin.userId);
      expect((admin.service as any).deleteUserRelatedData).toHaveBeenCalledWith(admin.userId, {
        avatarUrl: 'uploads/users/avatar/old.jpg',
        coverImageUrl: 'uploads/users/cover/old.jpg',
      });
      expect(admin.repository.deleteById).toHaveBeenCalledWith(admin.userId);
      expect(admin.audit.logSuperAdminAction).toHaveBeenCalledWith(
        'root',
        'admin_delete',
        'user',
        admin.userId,
      );
    });

    it('normalizes and audits an admin profile update', async () => {
      const { service, repository, audit, baseUser, userId } = createHarness({
        repository: {
          findById: jest.fn().mockResolvedValue({ ...createHarness().baseUser, role: UserRole.ADMIN }),
        },
      });

      await service.updateAdminBySuperAdmin('root', userId, {
        email: ' ADMIN@EXAMPLE.COM ',
      });

      expect(repository.updateById).toHaveBeenCalledWith(
        userId,
        expect.objectContaining({ email: 'admin@example.com' }),
      );
      expect(audit.logSuperAdminAction).toHaveBeenCalledWith(
        'root',
        'admin_update',
        'user',
        userId,
        { fields: ['email'] },
      );
      expect(baseUser).toBeDefined();
    });

    it('deletes a managed user through the cascade boundary and audits it', async () => {
      const { service, repository, audit, userId } = createHarness();
      (service as any).deleteUserRelatedData = jest.fn().mockResolvedValue(undefined);

      await service.deleteUserBySuperAdmin('root', userId);

      expect((service as any).deleteUserRelatedData).toHaveBeenCalled();
      expect(repository.deleteById).toHaveBeenCalledWith(userId);
      expect(audit.logSuperAdminAction).toHaveBeenCalledWith(
        'root',
        'user_delete',
        'user',
        userId,
      );
    });

    it('cascades user deletion across social/chat/marketplace data and managed media', async () => {
      const userId = new Types.ObjectId().toString();
      const postId = new Types.ObjectId();
      const ownCommentId = new Types.ObjectId();
      const postCommentId = new Types.ObjectId();
      const conversationId = new Types.ObjectId();
      const sequenceFind = (...values: Record<string, unknown>[][]) => {
        let index = 0;
        return jest.fn(() => {
          const value = values[index++] ?? [];
          const cursor = {
            project: jest.fn().mockReturnThis(),
            toArray: jest.fn().mockResolvedValue(value),
          };
          return cursor;
        });
      };
      const collections: Record<string, Record<string, jest.Mock>> = {
        posts: {
          find: sequenceFind([
            { _id: postId, videoUrl: 'uploads/post.mp4', audioUrl: 'uploads/post.mp3' },
          ]),
          deleteMany: jest.fn().mockResolvedValue({ deletedCount: 1 }),
        },
        comments: {
          find: sequenceFind([{ _id: ownCommentId }], [{ _id: postCommentId }]),
          deleteMany: jest.fn().mockResolvedValue({ deletedCount: 2 }),
        },
        likes: { deleteMany: jest.fn().mockResolvedValue({ deletedCount: 3 }) },
        saves: { deleteMany: jest.fn().mockResolvedValue({ deletedCount: 1 }) },
        follows: { deleteMany: jest.fn().mockResolvedValue({ deletedCount: 1 }) },
        notifications: { deleteMany: jest.fn().mockResolvedValue({ deletedCount: 1 }) },
        conversations: {
          find: sequenceFind([{ _id: conversationId }]),
          deleteMany: jest.fn().mockResolvedValue({ deletedCount: 1 }),
        },
        messages: {
          find: sequenceFind(
            [{ _id: new Types.ObjectId(), mediaUrl: 'uploads/own-message.jpg' }],
            [{ _id: new Types.ObjectId(), mediaUrl: 'uploads/conversation-message.jpg' }],
          ),
          deleteMany: jest.fn().mockResolvedValue({ deletedCount: 2 }),
        },
        chatblocks: { deleteMany: jest.fn().mockResolvedValue({ deletedCount: 1 }) },
        instruments: {
          find: sequenceFind([
            { _id: new Types.ObjectId(), imageUrls: ['uploads/instrument-1.jpg', 'uploads/instrument-2.jpg'] },
          ]),
          deleteMany: jest.fn().mockResolvedValue({ deletedCount: 1 }),
        },
        refreshtokens: { deleteMany: jest.fn().mockResolvedValue({ deletedCount: 1 }) },
        passwordresetcodes: { deleteMany: jest.fn().mockResolvedValue({ deletedCount: 1 }) },
        emailverificationcodes: { deleteMany: jest.fn().mockResolvedValue({ deletedCount: 1 }) },
      };
      const connection = {
        collection: jest.fn((name: string) => collections[name]),
      };
      const { service, repository, storage } = createHarness({
        connection,
        repository: {
          findById: jest.fn().mockResolvedValue({
            id: userId,
            role: UserRole.USER,
            avatar: 'uploads/avatar.jpg',
            coverImage: 'uploads/cover.jpg',
          }),
        },
      });

      await service.deleteUserBySuperAdmin('root', userId);

      expect(collections.likes.deleteMany).toHaveBeenCalledWith({
        $or: expect.arrayContaining([
          { userId: expect.any(Types.ObjectId) },
          { targetType: 'post', targetId: { $in: [postId] } },
          { targetType: 'comment', targetId: { $in: [ownCommentId, postCommentId] } },
        ]),
      });
      expect(collections.messages.deleteMany).toHaveBeenCalledTimes(2);
      expect(repository.deleteById).toHaveBeenCalledWith(userId);
      expect(storage.deleteFile.mock.calls.map(([path]) => path)).toEqual(
        expect.arrayContaining([
          'uploads/avatar.jpg',
          'uploads/cover.jpg',
          'uploads/post.mp4',
          'uploads/post.mp3',
          'uploads/own-message.jpg',
          'uploads/conversation-message.jpg',
          'uploads/instrument-1.jpg',
          'uploads/instrument-2.jpg',
        ]),
      );
    });

    it('returns presence defaults and delegates password-protected lookup', async () => {
      const { service, repository, userId } = createHarness();

      await expect(service.getPresence(userId)).resolves.toEqual({
        userId,
        isOnline: false,
        lastSeenAt: null,
      });
      await service.findByIdWithPassword(userId);
      expect(repository.findByIdWithPassword).toHaveBeenCalledWith(userId);
    });

    it('links Google identity and cleans a replaced avatar', async () => {
      const { service, repository, storage, userId } = createHarness();

      await service.linkGoogleAccount(userId, 'google-1', 'https://cdn.example.com/avatar.jpg');

      expect(repository.updateById).toHaveBeenCalledWith(userId, {
        googleId: 'google-1',
        authProvider: 'google',
        avatar: 'https://cdn.example.com/avatar.jpg',
      });
      expect(storage.deleteFile).toHaveBeenCalledWith('uploads/users/avatar/old.jpg');
    });

    it('accepts valid finite setup coordinates and delegates superadmin talent discovery', async () => {
      const { service, repository, userId } = createHarness();
      await service.updateProfileSetup(userId, { latitude: 24.7, longitude: 46.7 } as any);
      expect(repository.updateById).toHaveBeenCalledWith(
        userId,
        expect.objectContaining({ latitude: 24.7, longitude: 46.7 }),
      );

      const spy = jest.spyOn(service, 'discoverTalents').mockResolvedValue({ marker: true } as any);
      await expect(service.discoverTalentsForSuperAdmin({})).resolves.toEqual({ marker: true });
      expect(spy).toHaveBeenCalledWith({});
    });

    it.each(['updateMusicSetup', 'disableUserBySuperAdmin', 'enableUserBySuperAdmin'] as const)(
      '%s reports a vanished target instead of returning success',
      async (method) => {
        const { service, userId } = createHarness({
          repository: { updateById: jest.fn().mockResolvedValue(null) },
        });
        const promise =
          method === 'updateMusicSetup'
            ? service.updateMusicSetup(userId, { preferredMood: 'calm' })
            : method === 'disableUserBySuperAdmin'
              ? service.disableUserBySuperAdmin('root', userId, {})
              : service.enableUserBySuperAdmin('root', userId);
        await expect(promise).rejects.toBeInstanceOf(NotFoundException);
      },
    );

    it('forces safe viewer state in superadmin profile overview', async () => {
      const { service, userId } = createHarness();
      jest.spyOn(service, 'getProfileOverview').mockResolvedValue({
        viewerState: { isOwnProfile: true, following: true, isFollowing: true, canMessage: true },
      } as any);

      await expect(service.getProfileOverviewForSuperAdmin(userId)).resolves.toMatchObject({
        viewerState: {
          isOwnProfile: false,
          following: false,
          isFollowing: false,
          canMessage: false,
        },
      });
    });

    it('rejects invalid follow-count identities before accessing collections', async () => {
      const { service, connection } = createHarness();
      await expect(service.getFollowCounts('bad-id', 'also-bad')).rejects.toBeInstanceOf(
        BadRequestException,
      );
      expect(connection.collection).not.toHaveBeenCalled();
    });

    it('returns the minimal public filter when no optional filters are set', async () => {
      const { service, repository } = createHarness();
      await service.searchUsers({});
      expect(repository.findMany.mock.calls[0][0]).toEqual({ isDisabled: false });

      await service.searchUsersForSuperAdmin({});
      expect(repository.findMany.mock.calls[1][0]).toEqual({
        role: { $ne: UserRole.SUPERADMIN },
      });
    });
  });
});
