import * as plugins from '../../plugins.js';
import type { UnifiedEmailServer } from '../routing/classes.unified.email.server.js';
import { RustSecurityBridge } from '../../security/classes.rustsecuritybridge.js';

interface Headers {
  [key: string]: string;
}

interface IEmailSignJobOptions {
  domain: string;
  selector: string;
  headers: Headers;
  body: string;
}

export class EmailSignJob {
  emailServerRef: UnifiedEmailServer;
  jobOptions: IEmailSignJobOptions;

  constructor(emailServerRef: UnifiedEmailServer, options: IEmailSignJobOptions) {
    this.emailServerRef = emailServerRef;
    this.jobOptions = options;
  }

  async loadPrivateKey(): Promise<string> {
    const keyInfo = await this.emailServerRef.dkimCreator.readDKIMKeys(this.jobOptions.domain);
    return keyInfo.privateKey;
  }

  public async getSignatureHeader(emailMessage: string): Promise<string> {
    const privateKey = await this.loadPrivateKey();
    const bridge = RustSecurityBridge.getInstance();
    const signResult = await bridge.signDkim({
      rawMessage: emailMessage,
      domain: this.jobOptions.domain,
      selector: this.jobOptions.selector,
      privateKey,
    });
    return signResult.header;
  }
}
