/// <reference types="cypress" />
export {};

Cypress.env("AUTO_LOGIN", false);

const AUTH_COOKIE_KEYS = {
  accessToken: "TENDER_PANEL_token",
  refreshToken: "TENDER_PANEL_refresh_token",
  user: "TENDER_PANEL_user",
} as const;

const seedValidAuthCookies = () => {
  cy.setCookie(AUTH_COOKIE_KEYS.accessToken, "valid-e2e-token");
  cy.setCookie(AUTH_COOKIE_KEYS.refreshToken, "valid-e2e-refresh-token");
  cy.setCookie(
    AUTH_COOKIE_KEYS.user,
    encodeURIComponent(
      JSON.stringify({
        id: "507f1f77bcf86cd799439011",
        username: "e2e-admin",
        email: "e2e-admin@example.com",
        role: "admin",
      }),
    ),
  );
};

describe("conditional layout auth routing", () => {
  after(() => {
    Cypress.env("AUTO_LOGIN", true);
  });

  beforeEach(() => {
    cy.clearCookies();
    cy.clearLocalStorage();
  });

  it("shows dashboard page when user has a valid token", () => {
    seedValidAuthCookies();

    cy.visit("/");

    cy.location("pathname").should("eq", "/");
    cy.contains("Opportunity Lens").should("be.visible");
    cy.contains("Dashboard").should("be.visible");
  });

  it("redirects unauthenticated user to login page for protected route", () => {
    cy.visit("/admins");

    cy.location("pathname").should("eq", "/auth/sign-in");
    cy.contains("Welcome back").should("be.visible");
    cy.get('input[name="username"]').should("be.visible");
  });

  it("redirects authenticated user away from login page to dashboard", () => {
    seedValidAuthCookies();

    cy.visit("/auth/sign-in");

    cy.location("pathname").should("eq", "/");
    cy.contains("Opportunity Lens").should("be.visible");
  });

  it("redirects to login when token exists but user cookie is invalid", () => {
    cy.setCookie(AUTH_COOKIE_KEYS.accessToken, "invalid-session-token");
    cy.setCookie(AUTH_COOKIE_KEYS.user, "{invalid-json");

    cy.visit("/admins");

    cy.location("pathname").should("eq", "/auth/sign-in");
    cy.contains("Welcome back").should("be.visible");
  });
});
