import { DataSource } from 'typeorm';
import { getCurrentUserScope } from '../../current-user-scope';
import { PluginDataEntity } from '../../../entities';
import { SavePluginDataCommand } from '../../types';

export async function handleSavePluginData(command: SavePluginDataCommand, dataSource: DataSource): Promise<void> {
  const { payload } = command;
  const ownerUserId = await getCurrentUserScope(dataSource);

  if (!ownerUserId) {
    return;
  }

  await dataSource.getRepository(PluginDataEntity).save({
    key: payload.key,
    ownerUserId,
    pluginId: payload.pluginId,
    scope: payload.scope,
    serverId: payload.serverId ?? '',
    updatedAt: Date.now(),
    valueJson: JSON.stringify(payload.value ?? null)
  });
}
