const USER = {
  name: "John Wick",
};

describe("Login page", () => {
  before(() => {
    cy.log(`Visiting base url at localhost`);
    cy.visit("/");
  });

  it("Login with Google", () => {
    const username = Cypress.env("GOOGLE_USER");
    const password = Cypress.env("GOOGLE_PW");
    const loginUrl = Cypress.env("SITE_NAME");
    const cookieName = Cypress.env("COOKIE_NAME");
    const socialLoginOptions = {
      username,
      password,
      loginUrl,
      headless: true,
      logs: true,
      isPopup: true,
      loginSelector: `[data-testid="google-signin-btn"]`,
      postLoginSelector: `[data-testid="app-navbar"]`,
    };

    // Call cy.login() before cy.task()
    cy.login(USER);

    return cy.task("GoogleSocialLogin", socialLoginOptions).then(() => {
      cy.log("Logging in with cookies");

      // Check cookies with cy.getCookies() command after login and task are completed
      cy.getCookies().then((cookies) => {
        const cookie = cookies.find((cookie) => cookie.name === cookieName);
        cy.log("Cookie found!");

        if (cookie.length === 0) {
          cy.log("Cookie not found!");
          throw new Error(`Cookie '${cookieName}' not found!`);
        }

        cy.visit("/home");
        // After logging in, verify that we have navigated to the /home page.
        cy.log("Checking if we are on the /home page");
        cy.url().should("include", "/home");
        cy.log("We are on the /home page!");

        // remove the two lines below if you need to stay logged in
        // for your remaining tests
        cy.visit("/api/auth/signout");
        cy.get("form").submit();
      });
    });
  });
});
