import type { IUser } from '@api-client/core/models/store/User.js'
import { Events } from '../events/Events.js'

/**
 * A class that caches user info in memory so the application reduces the number
 * of requests to the backend requesting a user info.
 */
class UserCache {
  protected cached = new Map<string, IUser | undefined>()

  async getUser(organizationId: string, key: string): Promise<IUser | undefined> {
    const existing = this.cached.get(key)
    if (existing) {
      return existing
    }
    const read = await this.requestUser(organizationId, key)
    this.cached.set(key, read)
    return read
  }

  protected async requestUser(organizationId: string, key: string): Promise<IUser | undefined> {
    try {
      const result = await Events.Store.User.read(organizationId, key)
      return result
    } catch {
      // ....
    }
    return undefined
  }
}

const instance = new UserCache()
export default instance
