import { Page, Locator } from '@playwright/test';
import { EmailAction } from '../types';

export async function fromYopmail(
  page: Page,
  inbox: string,
  subjectName: string,
  actions: EmailAction[],
  deleteFlag?: boolean
): Promise<Record<string, any>> {
  await page.goto('https://yopmail.com/');
  await page.getByRole('textbox', { name: 'Login' }).fill(inbox);
  await page.getByRole('button', { name: '' }).click();

  if (subjectName) {
    const timeoutMs = 5 * 60 * 1000;
    const pollInterval = 10 * 1000;
    const start = Date.now();
    let found = false;

    while (Date.now() - start < timeoutMs) {
      const inboxFrame = await page.locator('iframe[name="ifinbox"]').contentFrame();
      try {
        await inboxFrame.getByRole('button', { name: subjectName }).waitFor({ timeout: pollInterval });
        await inboxFrame.getByRole('button', { name: subjectName }).click();
        found = true;
        break;
      } catch {
        await page.locator('#refresh').click();
        console.log('Waiting for email with subject');
      }
    }

    if (!found) {
      throw new Error(`Email with subject '${subjectName}' not found after 5 minutes.`);
    }
  }

  const results: Record<string, any> = {};

  for (const act of actions) {
    const frame = await page.locator('iframe[name="ifmail"]').contentFrame();
    let locator: Locator;

    if (act.selector.type === 'role') {
      locator = frame.getByRole(
        act.selector.value.role,
        act.selector.value.name ? { name: act.selector.value.name } : undefined
      );
    } else if (act.selector.type === 'text') {
      locator = frame.getByText(act.selector.value);
    } else {
      locator = frame.locator(act.selector.value);
    }

    let result;
    if (act.action === 'click') {
      await locator.first().click();
      result = 'clicked';
    } else if (act.action === 'textContent') {
      result = await locator.first().textContent();
    } else if (act.action === 'getAttribute') {
      result = await locator.first().getAttribute(act.attributeName!);
    }

    results[act.description] = result;
  }

  if (deleteFlag && subjectName) {
    const inboxFrame = await page.locator('iframe[name="ifinbox"]').contentFrame();
    const emailButton = inboxFrame.getByRole('button', { name: subjectName });
    const checkbox = emailButton.locator('..').getByRole('checkbox');
    await checkbox.check();
    await page.locator('#delsel').click();
  }

  return results;
}