import { BadRequestException } from '@nestjs/common';

const UUID_PATTERN =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

const ALLOWED_EXACT_PATHS = new Set(['/dashboard', '/servers']);

const ALLOWED_SERVER_SUBPAGES = new Set([
  'console',
  'files',
  'properties',
  'players',
  'worlds',
  'backups',
  'addons',
]);

export function resolveSsoTargetPath(
  requestedPath: string | undefined,
  serverId: string,
): string {
  const defaultPath = `/servers/${serverId}`;

  if (!requestedPath || requestedPath.trim() === '') {
    return defaultPath;
  }

  const trimmed = requestedPath.trim();

  if (
    trimmed.includes('://') ||
    trimmed.startsWith('//') ||
    trimmed.includes('\\') ||
    trimmed.includes('\0')
  ) {
    throw new BadRequestException('Target path must be a relative application path');
  }

  const path = trimmed.startsWith('/') ? trimmed : `/${trimmed}`;

  if (ALLOWED_EXACT_PATHS.has(path)) {
    return path;
  }

  if (!path.startsWith(`/servers/${serverId}`)) {
    throw new BadRequestException('Target path must reference the linked server');
  }

  if (path === `/servers/${serverId}`) {
    return path;
  }

  const suffix = path.slice(`/servers/${serverId}`.length);
  const subpage = suffix.startsWith('/') ? suffix.slice(1) : suffix;

  if (subpage && ALLOWED_SERVER_SUBPAGES.has(subpage)) {
    return `/servers/${serverId}/${subpage}`;
  }

  throw new BadRequestException('Target path is not allowlisted');
}

export function isUuid(value: string): boolean {
  return UUID_PATTERN.test(value);
}
