import { AuthUserEntity } from '../entities/AuthUserEntity';
import { ServerEntity } from '../entities/ServerEntity';
import { JoinRequestEntity } from '../entities/JoinRequestEntity';
import {
  AuthUserPayload,
  ServerPayload,
  JoinRequestPayload
} from './types';
import { relationRecordToServerPayload } from './relations';

export function rowToAuthUser(row: AuthUserEntity): AuthUserPayload {
  return {
    id: row.id,
    username: row.username,
    passwordHash: row.passwordHash,
    displayName: row.displayName,
    createdAt: row.createdAt,
    signingPublicKey: row.signingPublicKey ?? null
  };
}

export function rowToServer(
  row: ServerEntity,
  relations: Pick<ServerPayload, 'tags' | 'channels' | 'roles' | 'roleAssignments' | 'channelPermissions'> = {
    tags: [],
    channels: [],
    roles: [],
    roleAssignments: [],
    channelPermissions: []
  }
): ServerPayload {
  const relationPayload = relationRecordToServerPayload({ slowModeInterval: row.slowModeInterval }, {
    tags: relations.tags ?? [],
    channels: relations.channels ?? [],
    roles: relations.roles ?? [],
    roleAssignments: relations.roleAssignments ?? [],
    channelPermissions: relations.channelPermissions ?? []
  });

  return {
    id: row.id,
    name: row.name,
    description: row.description ?? undefined,
    ownerId: row.ownerId,
    ownerPublicKey: row.ownerPublicKey,
    hasPassword: !!row.passwordHash,
    passwordHash: row.passwordHash ?? undefined,
    isPrivate: !!row.isPrivate,
    maxUsers: row.maxUsers,
    currentUsers: row.currentUsers,
    icon: row.icon ?? undefined,
    iconUpdatedAt: row.iconUpdatedAt || undefined,
    slowModeInterval: relationPayload.slowModeInterval,
    tags: relationPayload.tags,
    channels: relationPayload.channels,
    roles: relationPayload.roles,
    roleAssignments: relationPayload.roleAssignments,
    channelPermissions: relationPayload.channelPermissions,
    createdAt: row.createdAt,
    lastSeen: row.lastSeen
  };
}

export function rowToJoinRequest(row: JoinRequestEntity): JoinRequestPayload {
  return {
    id: row.id,
    serverId: row.serverId,
    userId: row.userId,
    userPublicKey: row.userPublicKey,
    displayName: row.displayName,
    status: row.status as JoinRequestPayload['status'],
    createdAt: row.createdAt
  };
}
