import { DataSource } from 'typeorm';
import { RoomEntity, RoomOwnerEntity } from '../../../entities';
import { replaceRoomRelations } from '../../relations';
import { SaveRoomCommand } from '../../types';
import { getCurrentUserScope } from '../../current-user-scope';

function extractSlowModeInterval(room: SaveRoomCommand['payload']['room']): number {
  if (typeof room.slowModeInterval === 'number' && Number.isFinite(room.slowModeInterval)) {
    return room.slowModeInterval;
  }

  const permissions = room.permissions && typeof room.permissions === 'object'
    ? room.permissions as { slowModeInterval?: unknown }
    : null;

  return typeof permissions?.slowModeInterval === 'number' && Number.isFinite(permissions.slowModeInterval)
    ? permissions.slowModeInterval
    : 0;
}

export async function handleSaveRoom(command: SaveRoomCommand, dataSource: DataSource): Promise<void> {
  const { room } = command.payload;

  await dataSource.transaction(async (manager) => {
    const currentUserId = await getCurrentUserScope(manager);
    const repo = manager.getRepository(RoomEntity);
    const entity = repo.create({
      id: room.id,
      name: room.name,
      description: room.description ?? null,
      topic: room.topic ?? null,
      hostId: room.hostId,
      password: room.password ?? null,
      hasPassword: room.hasPassword ? 1 : 0,
      isPrivate: room.isPrivate ? 1 : 0,
      createdAt: room.createdAt,
      userCount: room.userCount ?? 0,
      maxUsers: room.maxUsers ?? null,
      icon: room.icon ?? null,
      iconUpdatedAt: room.iconUpdatedAt ?? null,
      slowModeInterval: extractSlowModeInterval(room),
      sourceId: room.sourceId ?? null,
      sourceName: room.sourceName ?? null,
      sourceUrl: room.sourceUrl ?? null
    });

    await repo.save(entity);

    if (currentUserId) {
      await manager.getRepository(RoomOwnerEntity).save({
        roomId: room.id,
        userId: currentUserId,
        savedAt: Date.now()
      });
    }

    await replaceRoomRelations(manager, room.id, {
      channels: room.channels ?? [],
      members: room.members ?? [],
      roles: room.roles ?? [],
      roleAssignments: room.roleAssignments ?? [],
      channelPermissions: room.channelPermissions ?? [],
      permissions: room.permissions
    });
  });
}
