import {getAllUsers} from '@modules/chats/db/repositories/users';
import {ChatUserStatus} from '@modules/chats/interfaces';

export type ShortedUser = {
  id: number;
  first_name: string;
  last_name: string;
  profile_picture: Nullable<string>;
  status: ChatUserStatus;
  deleted_at: Nullable<number>;
};

export class UsersMapper {
  private users: Map<number, ShortedUser> = new Map();

  /**
   * Save or update multiple users in the store
   */
  save(newUsers: ShortedUser[]): void {
    newUsers.forEach(user => {
      this.users.set(user.id, user);
    });
  }

  /**
   * Initialize the users store by loading users from the database
   */
  async init(): Promise<void> {
    const usersFromDB = await getAllUsers();
    usersFromDB.forEach(user => {
      this.users.set(user.id, {
        id: user.id,
        first_name: user.first_name,
        last_name: user.last_name,
        profile_picture: user.picture_asset_url || null,
        status: user.status as ChatUserStatus,
        deleted_at: user.deleted_at,
      });
    });
  }

  /**
   * Clear all users from the store
   */
  clear(): void {
    this.users.clear();
  }

  /**
   * Get a specific user by ID
   */
  get(userId: number): ShortedUser | undefined {
    return this.users.get(userId);
  }

  /**
   * Get all users as a Map
   */
  getAll(): Map<number, ShortedUser> {
    return new Map(this.users); // Return a copy to prevent external mutations
  }

  /**
   * Check if a user exists in the store
   */
  has(userId: number): boolean {
    return this.users.has(userId);
  }

  /**
   * Get the number of users in the store
   */
  getCount(): number {
    return this.users.size;
  }
}

// Export a singleton instance
export const usersMapper = new UsersMapper();
