import { Selector } from "testcafe";
import {
  getSiteRoot, getPageUrl, generateTestEvent, generateTestForm, deleteEvent, deleteForm, generateToken,
} from "./utils";

fixture`Event signup`.page(getSiteRoot())
  .before(async (ctx) => {
    const token = await generateToken();
    const form = await generateTestForm(token);
    const event = await generateTestEvent([form.id], token);
    ctx.eventId = event.id;
    ctx.formId = form.id;
  })
  .after(async (ctx) => {
    const token = await generateToken();
    await deleteEvent(ctx.eventId, token);
    await deleteForm(ctx.formId, token);
  });

test("User signups to event from front page", async (t) => {
  // Force refresh, so that ISR updates front page events and creates the pages created in before()
  await t.wait(15000);
  await t.navigateTo("/");
  await t.wait(5000);
  await t.navigateTo("/");

  const CardSelector = Selector("[data-e2e=\"event-card\"]").withText("title_fi").nth(0);

  await t
    .click(CardSelector.child("a"));

  await t.wait(3000);
  await t.expect(await getPageUrl()).match(/\/events\/\d{1,4}/, "URL isn't /events/<id>");

  const SignupButton = Selector("[data-e2e=\"signup-button\"]");
  await t
    .click(SignupButton);

  await t.wait(3000);
  await t.expect(await getPageUrl()).match(/\/signup\/\d{1,4}/, "URL isn't /signup/<id>");

  const nameField = Selector("input").nth(0);
  const emailField = Selector("input").nth(1);
  const typeField = Selector("fieldset").child(-1).child("div").child("div")
    .child("label")
    .nth(-1);

  await t
    .typeText(nameField, "Testi Testeri")
    .typeText(emailField, "e2e@sahkoinsinoorikilta.fi")
    .click(typeField);

  await t.click(Selector("button").nth(-1));

  const statusMessage = Selector(".Toastify__toast-body");
  await t
    .hover(statusMessage)
    .expect(
      statusMessage.innerText,
    ).eql("Sign-up submitted successfully 😎");
});
