import * as plugins from '../../plugins.js';
import type { UnifiedEmailServer } from '../routing/classes.unified.email.server.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 signResult = await plugins.dkimSign(emailMessage, {
      signingDomain: this.jobOptions.domain,
      selector: this.jobOptions.selector,
      privateKey,
      canonicalization: 'relaxed/relaxed',
      algorithm: 'rsa-sha256',
      signTime: new Date(),
      signatureData: [
        {
          signingDomain: this.jobOptions.domain,
          selector: this.jobOptions.selector,
          privateKey,
          algorithm: 'rsa-sha256',
          canonicalization: 'relaxed/relaxed',
        },
      ],
    });
    const signature = signResult.signatures;
    return signature;
  }
}
