export function createNonce(): string {
  return crypto.randomUUID().replaceAll('-', '');
}

export function buildContentSecurityPolicy(
  nonce: string,
  development: boolean,
  apiOrigin?: string,
): string {
  void nonce;
  const scriptSources = ["'self'", "'unsafe-inline'", "'unsafe-eval'"];

  const styleSources = ["'self'", "'unsafe-inline'"];

  const connectSources = ["'self'"];
  if (development) connectSources.push('ws:', 'wss:');
  if (apiOrigin) connectSources.push(apiOrigin);

  const directives = [
    "default-src 'self'",
    `script-src ${scriptSources.join(' ')}`,
    `style-src ${styleSources.join(' ')}`,
    "img-src 'self' data: blob:",
    "font-src 'self' data:",
    `connect-src ${connectSources.join(' ')}`,
    "media-src 'self'",
    "object-src 'none'",
    "base-uri 'self'",
    "form-action 'self'",
    "frame-ancestors 'none'",
    "worker-src 'self' blob:",
    ...(development ? [] : ['upgrade-insecure-requests']),
  ];
  return directives.join('; ');
}
