import { randomUUID } from 'node:crypto';
import fs from 'node:fs';

import { deviceIdPath } from './paths';

export function getOrCreateDeviceId(userData: string): string {
  const p = deviceIdPath(userData);
  try {
    const existing = fs.readFileSync(p, 'utf8').trim();
    if (existing.length >= 8) return existing;
  } catch {
    /* empty */
  }
  const id = randomUUID();
  fs.mkdirSync(userData, { recursive: true });
  fs.writeFileSync(p, `${id}\n`, 'utf8');
  return id;
}
