import { APIRequestContext, expect, Page, Request } from "@playwright/test";
import { BasePage } from "../base.page";

export class Mail extends BasePage {
    mailUrl: string;

    constructor(page: Page, request: APIRequestContext) {
        super(page, request);
        this.mailUrl = process.env.MAIL_SERVER || 'http://69.28.90.112:8025/'
    }

    get mailLoc() {
        return {
            btnOpenNotification: this.genLoc("//span[text()='Adjust email notifications for this request']"),
            titleMail: (title: string) => this.genLoc(`//b[contains(text(),'${title}')]`),
            openButton: this.genLoc('//a[contains(text(),"Open")]'),
            mailFrame: this.genFrameLoc("//iframe[@class='tab-pane d-block']"),
            mailContent: this.genLoc("//table[@class='es-header-body']/tbody")
        }
    }

    async open() {
        await this.page.goto(this.mailUrl);
    }

    async findMail(title: string, toEmail: string = '') {
        // Call API to get mails
        const rawResponse = await this.request.get(`${this.mailUrl}/api/v1/messages`);
        expect(rawResponse.status()).toEqual(200);
        const response = await rawResponse.json();
        const messages = await response.messages;

        const mail = messages.find(item => {
            return item.To[0].Address.includes(toEmail) && item.Subject.includes(title);
        })

        return mail;
    }
}