import fs from 'node:fs/promises';
import path from 'node:path';

const distDir = path.resolve(process.cwd(), 'dist');
const swCandidates = ['sw.js', 'service-worker.js'];

async function fileExists(filePath) {
  try {
    await fs.access(filePath);
    return true;
  } catch {
    return false;
  }
}

async function main() {
  const swPath = await (async () => {
    for (const name of swCandidates) {
      const fullPath = path.join(distDir, name);
      if (await fileExists(fullPath)) return fullPath;
    }
    return null;
  })();

  if (!swPath) {
    throw new Error('Service worker file not found in dist/.');
  }

  const swContent = await fs.readFile(swPath, 'utf8');
  const required = [
    /offline\.html/,
    /atividades\/letramento\//,
    /letramento\.css/,
    /lucide\.js/,
  ];

  const missing = required.filter((regex) => !regex.test(swContent));
  if (missing.length > 0) {
    throw new Error(`Precache entries missing: ${missing.map(String).join(', ')}`);
  }

  console.log('Cache test passed.');
}

main().catch((err) => {
  console.error(err.message);
  process.exit(1);
});
