import * as interfaces from '../ts_interfaces/index.js';
import type { DcRouterApiClient } from './classes.dcrouterapiclient.js';

export class Email {
  private clientRef: DcRouterApiClient;

  // Data from IEmail
  public id: string;
  public direction: interfaces.requests.TEmailDirection;
  public status: interfaces.requests.TEmailStatus;
  public from: string;
  public to: string;
  public subject: string;
  public timestamp: string;
  public messageId: string;
  public size: string;

  constructor(clientRef: DcRouterApiClient, data: interfaces.requests.IEmail) {
    this.clientRef = clientRef;
    this.id = data.id;
    this.direction = data.direction;
    this.status = data.status;
    this.from = data.from;
    this.to = data.to;
    this.subject = data.subject;
    this.timestamp = data.timestamp;
    this.messageId = data.messageId;
    this.size = data.size;
  }

  public async getDetail(): Promise<interfaces.requests.IEmailDetail | null> {
    const response = await this.clientRef.request<interfaces.requests.IReq_GetEmailDetail>(
      'getEmailDetail',
      this.clientRef.buildRequestPayload({ emailId: this.id }) as any,
    );
    return response.email;
  }

  public async resend(): Promise<{ success: boolean; newQueueId?: string }> {
    const response = await this.clientRef.request<interfaces.requests.IReq_ResendEmail>(
      'resendEmail',
      this.clientRef.buildRequestPayload({ emailId: this.id }) as any,
    );
    return response;
  }
}

export class EmailManager {
  private clientRef: DcRouterApiClient;

  constructor(clientRef: DcRouterApiClient) {
    this.clientRef = clientRef;
  }

  public async list(): Promise<Email[]> {
    const response = await this.clientRef.request<interfaces.requests.IReq_GetAllEmails>(
      'getAllEmails',
      this.clientRef.buildRequestPayload() as any,
    );
    return response.emails.map((e) => new Email(this.clientRef, e));
  }

  public async getDetail(emailId: string): Promise<interfaces.requests.IEmailDetail | null> {
    const response = await this.clientRef.request<interfaces.requests.IReq_GetEmailDetail>(
      'getEmailDetail',
      this.clientRef.buildRequestPayload({ emailId }) as any,
    );
    return response.email;
  }

  public async resend(emailId: string): Promise<{ success: boolean; newQueueId?: string }> {
    return this.clientRef.request<interfaces.requests.IReq_ResendEmail>(
      'resendEmail',
      this.clientRef.buildRequestPayload({ emailId }) as any,
    );
  }
}
