import { safeStorage } from 'electron';
import {
  mkdir,
  readFile,
  writeFile
} from 'fs/promises';
import path from 'path';
import { app } from 'electron';

const STORAGE_DIR_NAME = 'provision-secrets';

function getStorageDir(): string {
  return path.join(app.getPath('userData'), STORAGE_DIR_NAME);
}

function getSecretFilePath(homeUserId: string): string {
  return path.join(getStorageDir(), `${homeUserId}.bin`);
}

async function ensureStorageDir(): Promise<void> {
  await mkdir(getStorageDir(), { recursive: true });
}

export async function storeProvisionSecret(homeUserId: string, secret: string): Promise<boolean> {
  if (!homeUserId.trim() || !secret) {
    return false;
  }

  await ensureStorageDir();

  if (!safeStorage.isEncryptionAvailable()) {
    await writeFile(getSecretFilePath(homeUserId), secret, 'utf8');
    return true;
  }

  const encrypted = safeStorage.encryptString(secret);

  await writeFile(getSecretFilePath(homeUserId), encrypted);

  return true;
}

export async function getProvisionSecret(homeUserId: string): Promise<string | null> {
  if (!homeUserId.trim()) {
    return null;
  }

  try {
    const filePath = getSecretFilePath(homeUserId);
    const payload = await readFile(filePath);

    if (!safeStorage.isEncryptionAvailable()) {
      return payload.toString('utf8');
    }

    return safeStorage.decryptString(payload);
  } catch {
    return null;
  }
}
