import { DataSource } from 'typeorm';
import { ServerEntity } from '../../../entities';
import { replaceServerRelations } from '../../relations';
import { UpsertServerCommand } from '../../types';

export async function handleUpsertServer(command: UpsertServerCommand, dataSource: DataSource): Promise<void> {
  const { server } = command.payload;

  await dataSource.transaction(async (manager) => {
    const repo = manager.getRepository(ServerEntity);
    const entity = repo.create({
      id: server.id,
      name: server.name,
      description: server.description ?? null,
      ownerId: server.ownerId,
      ownerPublicKey: server.ownerPublicKey,
      passwordHash: server.passwordHash ?? null,
      isPrivate: server.isPrivate ? 1 : 0,
      maxUsers: server.maxUsers,
      currentUsers: server.currentUsers,
      icon: server.icon ?? null,
      iconUpdatedAt: server.iconUpdatedAt ?? 0,
      slowModeInterval: server.slowModeInterval ?? 0,
      createdAt: server.createdAt,
      lastSeen: server.lastSeen
    });

    await repo.save(entity);
    await replaceServerRelations(manager, server.id, {
      tags: server.tags,
      channels: server.channels ?? [],
      roles: server.roles ?? [],
      roleAssignments: server.roleAssignments ?? [],
      channelPermissions: server.channelPermissions ?? []
    });
  });
}
