import test from 'ava';
import {sleep, expect, tid, playstart, playstop, form, wait} from '../../lib/testing.js';
import faker from 'faker';
import {knex} from '../../lib/ormish.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/#/register/`));

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

test('register form error', async (t) => {
  const {context, p} = t.context;
  t.not(context, undefined);

  let res;

  try {
    // confirm we get errors
    await p.click(tid("register-button"));
    let email_error = await p.textContent(tid("email-error-0"));
    t.true(email_error.includes("email field is required"));

    // BUG: this will jam up if there's an error
    const user = {
      email: faker.internet.email(),
      full_name: faker.name.findName(),
      initials: 'XX',
      password: faker.internet.password(),
    }

    await form(p, {
      "#email": user.email,
      "#full_name": user.full_name,
      "#initials": "XXX",
      "#password": user.password,
      "#password_repeat": user.password,
      "#tos_agree": true,
    }, tid("register-button"));

    t.is(await p.$(tid("email-error")), null);

    await sleep(1000); // need this slight delay to keep playwright happy

    res = await knex('user').where({email: user.email.toLowerCase()}).select();

    t.not(res, undefined);
    t.not(res.length, 0);

    const fake_cancel = await p.$(tid("fake-payment-cancel"));

    if(fake_cancel) {
      // if the server is in fake mode, continue with the test
      await fake_cancel.click();
      await expect(t, p, tid("payment-error"));
      await p.click(tid("try-again"));

      // cause a fake error
      await wait(p, tid("fake-payment-error"));
      const fake_error = await p.$(tid("fake-payment-error"));
      t.not(fake_error, null);
      await fake_error.click();
      await p.click(tid("try-again"));

      // click finish payment
      await wait(p, tid("fake-payment-button"));
      const fake_pay = await p.$(tid("fake-payment-button"));
      t.not(fake_pay, null);
      await fake_pay.click();

      // confirm payment went through
      await wait(p, tid("get-started"));
      // confirm it's in the dialogue
      await p.click(tid("get-started"));
      await expect(t, p, tid("home-page"));
    } else {
      console.error("Fake Payment mode not enabled, can't test.");
    }

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