import { readFile, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';

const swPath = resolve(process.cwd(), 'public', 'sw.js');
const buildStamp = `${Date.now()}`;

const source = await readFile(swPath, 'utf8');
const next = source.replace(
  /const CACHE_NAME = 'radioplayer-pwa-v5(?:-[^']+)?';/,
  `const CACHE_NAME = 'radioplayer-pwa-v5-${buildStamp}';`,
);

if (next === source) {
  throw new Error('Failed to update service worker cache version.');
}

await writeFile(swPath, next, 'utf8');