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

export async function handleGetPluginData(query: GetPluginDataQuery, dataSource: DataSource): Promise<unknown> {
  const { payload } = query;
  const ownerUserId = await getCurrentUserScope(dataSource);

  if (!ownerUserId) {
    return null;
  }

  const record = await dataSource.getRepository(PluginDataEntity).findOne({
    where: {
      key: payload.key,
      ownerUserId,
      pluginId: payload.pluginId,
      scope: payload.scope,
      serverId: payload.serverId ?? ''
    }
  });

  if (!record) {
    return null;
  }

  try {
    return JSON.parse(record.valueJson) as unknown;
  } catch {
    return null;
  }
}
