import test from 'ava';
import { sleep, login, expect, tid, register_user, playstart, playstop} from '../../lib/testing.js';
import { User } from "../../lib/models.js";
import { base_host } from "../../lib/config.js";

test.before(async t => t.context = await playstart(`${base_host}/client/#/login/`));

test.after(async t => {
  await playstop(t.context.browser, t.context.p);
});

test('test /admin/email/ works', async (t) => {
  const {p} = t.context;
  let user;

  try {
    let user = await register_user(true);
    t.is(user.admin, true);
    t.not(user.email, undefined);
    user = await login(t, p, user);

    await p.goto(`${base_host}/admin/#/email-send/`);

    // test the send test
    await expect(t, p, tid("page-admin-email-send"));
    await p.fill("#to_address", user.email);
    await p.click(tid("send-button"));
    await expect(t, p, tid("result-message"));

    // test the dns resolve checker
    await p.click(tid("sidebar-link-Email DNS"));
    await expect(t, p, tid("domain-input"));
    await p.fill("#domain_name", "xor.academy");
    await p.press("#domain_name", "Enter");

    await expect(t, p, tid("domain-result"));

    // now try a bad domain

    await p.fill("#domain_name", "doesnotexist.xor.academy");
    await p.press("#domain_name", "Enter");
    await expect(t, p, tid("domain-result"));

    await sleep(2000);
    await expect(t, p, tid("error-dns"));

  } catch (error) {
    console.log(error);
    t.fail(error.message);
  } finally {
    if(user) await User.delete({id: user.id});
  }
});
