// src/services/crypto.ts
// Copyright (C) 2026 Robert Colbert <rob.colbert@openplatform.us>
// All Rights Reserved

import { DtpService } from "../lib/service.js";
import env from "../config/env.js";
import assert from "node:assert";

import crypto from "node:crypto";

class CryptoService extends DtpService {
  get name(): string {
    return "CryptoService";
  }
  get slug(): string {
    return "crypto";
  }

  async start(): Promise<void> {}
  async stop(): Promise<void> {}

  async maskPassword(passwordSalt: string, password: string): Promise<string> {
    assert(env.user.passwordSalt, "Password salt is required");
    const hash = crypto.createHash("sha256");

    hash.update(env.user.passwordSalt); // environment
    hash.update(passwordSalt); // per-user
    hash.update(password);

    return hash.digest("hex");
  }

  createHash(content: string | Buffer, algorithm: string = "sha256"): string {
    const hash = crypto.createHash(algorithm);
    hash.update(content);
    return hash.digest("hex");
  }

  createHmac(
    secret: string,
    content: string | Buffer,
    algorithm: string = "sha256"
  ): string {
    const hmac = crypto.createHmac(algorithm, secret);
    hmac.update(content);
    return hmac.digest("hex");
  }
}

export default new CryptoService();
