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

export function buildContentSecurityPolicy(
  nonce: string,
  development: boolean,
  apiOrigin?: string,
): string {
  const scriptSources = ["'self'", `'nonce-${nonce}'`, "'strict-dynamic'"];
  if (development) scriptSources.push("'unsafe-eval'");

  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 'self'${development ? " 'unsafe-inline'" : ` 'nonce-${nonce}'`}`,
    "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('; ');
}
