import { DataSource, EntityManager } from 'typeorm';
import { MetaEntity, RoomOwnerEntity } from '../entities';

export async function getCurrentUserScope(dataSourceOrManager: DataSource | EntityManager): Promise<string | null> {
  const repo = dataSourceOrManager.getRepository(MetaEntity);
  const meta = await repo.findOne({ where: { key: 'currentUserId' } });

  return meta?.value?.trim() || null;
}

export async function userOwnsRoom(
  dataSourceOrManager: DataSource | EntityManager,
  roomId: string,
  userId: string | null
): Promise<boolean> {
  if (!userId) {
    return false;
  }

  const repo = dataSourceOrManager.getRepository(RoomOwnerEntity);
  const owner = await repo.findOne({ where: { roomId, userId } });

  return !!owner;
}
