import { randomBytes } from 'node:crypto';
import { chmod, readFile, writeFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const scriptDirectory = dirname(fileURLToPath(import.meta.url));
const envPath = resolve(scriptDirectory, '..', '.env');
const secretNames = [
  'AUTH_ACCESS_TOKEN_SECRET',
  'AUTH_REFRESH_TOKEN_SECRET',
  'STORAGE_SIGNING_SECRET',
  'BACKUP_CRON_SECRET',
  'RENOVACOES_CRON_SECRET',
  'VD_PENDENCIAS_CRON_SECRET',
] as const;

function generateSecret(): string {
  return randomBytes(64).toString('base64url');
}

const original = await readFile(envPath, 'utf8');
let updated = original;
const generated: string[] = [];

for (const name of secretNames) {
  const expression = new RegExp(`^${name}=(.*)$`, 'm');
  const match = expression.exec(updated);
  if (!match) {
    updated += `${updated.endsWith('\n') ? '' : '\n'}${name}=${generateSecret()}\n`;
    generated.push(name);
    continue;
  }

  if ((match[1] ?? '').trim() === '') {
    updated = updated.replace(expression, `${name}=${generateSecret()}`);
    generated.push(name);
  }
}

if (updated !== original) {
  await writeFile(envPath, updated, { encoding: 'utf8', mode: 0o600 });
  await chmod(envPath, 0o600).catch(() => undefined);
}

console.log(
  generated.length > 0
    ? `Generated ${generated.length} missing local secret(s).`
    : 'All local secrets already exist.',
);
