import { type DataTable, Given, Then, When } from "@badeball/cypress-cucumber-preprocessor";
import { ErrorCode } from "@batch-cooking/shared";

const signupResponse = {
  id: 1,
  firstName: "Alice",
  lastName: "Martin",
  email: "alice@example.com",
  tokenVersion: 0,
  houseId: null as number | null,
  dietId: null,
};

Given("the signup request will succeed", () => {
  cy.intercept("POST", "**/auth/signup", { statusCode: 201, body: signupResponse }).as("signup");
});

Given("the signup request is being watched", () => {
  cy.intercept("POST", "**/auth/signup").as("signup");
});

Given("the signup request will fail because the email is already used", () => {
  cy.intercept("POST", "**/auth/signup", {
    statusCode: 409,
    body: { code: ErrorCode.EMAIL_ALREADY_IN_USE, message: "Email already in use" },
  }).as("signup");
});

When("I sign up with:", (dataTable: DataTable) => {
  const { firstName, lastName, email, password } = dataTable.rowsHash();
  cy.visit("/signup");
  cy.get("#firstName").type(firstName);
  cy.get("#lastName").type(lastName);
  cy.get("#email").type(email);
  cy.get("#password").type(password);
  cy.contains("button", "Créer mon profil").click();
});

Then("the signup request should have been made", () => {
  cy.wait("@signup");
});

Then("the signup request should not have been made", () => {
  cy.get("@signup.all").should("have.length", 0);
});

Given("the login request will succeed", () => {
  cy.intercept("POST", "**/auth/login", {
    statusCode: 200,
    body: { ...signupResponse, houseId: 1 },
  }).as("login");
});

Given("the login request will fail because the credentials are invalid", () => {
  cy.intercept("POST", "**/auth/login", {
    statusCode: 401,
    body: { code: ErrorCode.INVALID_CREDENTIALS, message: "Invalid email or password" },
  }).as("login");
});

When("I log in with email {string} and password {string}", (email: string, password: string) => {
  cy.visit("/login");
  cy.get("#email").type(email);
  cy.get("#password").type(password);
  cy.contains("button", "Se connecter").click();
});

Then("the login request should have been made", () => {
  cy.wait("@login");
});

Given("the logout request will succeed", () => {
  cy.intercept("POST", "**/auth/logout", { statusCode: 204 }).as("logout");
});

Then("the logout request should have been made", () => {
  cy.wait("@logout");
});
