import { injectable } from 'inversify';
import { Database, getConnection } from '../../core/database';
import { StoreValue } from '../../entities/store/store-value';
import { IStore } from './i-store';

const CACHE_ID = 'store';

@injectable()
export class Store implements IStore {
  public async load(key: StoreKey): Promise<unknown> {
    const c = await getConnection(Database.STORE);
    const repository = c.getRepository(StoreValue);
    const storeValue = await repository.findOne(key, {
      cache: {
        id: CACHE_ID,
        milliseconds: 0,
      },
    });
    return storeValue?.value;
  }

  public async save(key: StoreKey, data: unknown): Promise<void> {
    const c = await getConnection(Database.STORE);
    const { manager } = c;
    const storeValue = new StoreValue();
    storeValue.key = key;
    storeValue.value = data;
    await manager.save(storeValue);
    await c.queryResultCache?.remove([CACHE_ID]);
  }
}
