import test from 'ava';
import {sleep, login, register_user, tid, expect, 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/#/forgot`));

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

test('test /forgot works', async (t) => {
  const {p} = t.context;

  try {
    // register a fake user so we can reset their password
    const user = await register_user();

    // confirm we get errors
    await expect(t, p, tid("page-password-reset"));

    await p.fill("#email", user.email);
    await p.click(tid("reset-button"));
    await expect(t, p, tid("reset-email-sent"));

    // query the db to get the code, have to poll for it
    let u2 = await User.first({email: user.email});
    for(let i = 0; i < 20 && u2.reset_code === null; i++) {
      await sleep(200);
      u2 = await User.first({email: user.email});
    }

    t.not(u2.reset_code, null);
    const test_password = "newtestmeyes";

    await p.fill("#code", u2.reset_code);
    await p.fill("#password", test_password);
    await p.fill("#password_repeat", test_password);
    await p.click(tid("reset-button"));

    await expect(t, p, tid("reset-complete-message"));
    await p.click(tid("login-button"));

    // then attempt to login with the new password
    u2.raw_password = test_password;
    const u3 = await login(t, p, u2);
  } catch (error) {
    console.log(error);
    t.fail(error.message);
  }
});
