import { Given, Then, When } from "@badeball/cypress-cucumber-preprocessor";

const houseWithTwoMembers = {
  id: 1,
  name: "Chez Alice",
  adminId: 1,
  inviteCode: "ABCD2345",
  members: [
    { id: 1, firstName: "Alice", lastName: "Martin" },
    { id: 2, firstName: "Bob", lastName: "Dupont" },
  ],
};

Given("the household request returns the two-member household", () => {
  cy.intercept("GET", "**/house/current", { statusCode: 200, body: houseWithTwoMembers });
});

// Creating/joining a household, and asserting on those two requests, is
// shared with onboarding.feature's household step — see
// cypress/support/step_definitions/household-mutations.steps.ts.

Given("renaming the household will succeed", () => {
  cy.intercept("PATCH", "**/house/current", {
    statusCode: 200,
    body: { ...houseWithTwoMembers, name: "Chez les Martin" },
  }).as("renameHouse");
});

Given("removing Bob from the household will succeed", () => {
  const householdWithoutBob = { ...houseWithTwoMembers, members: [houseWithTwoMembers.members[0]] };
  let memberRemoved = false;
  cy.intercept("GET", "**/house/current", (req) => {
    req.reply({ statusCode: 200, body: memberRemoved ? householdWithoutBob : houseWithTwoMembers });
  });
  cy.intercept("DELETE", "**/house/members/2", (req) => {
    memberRemoved = true;
    req.reply({ statusCode: 200, body: householdWithoutBob });
  }).as("removeMember");
});

Given("deleting the household will succeed", () => {
  let houseDeleted = false;
  cy.intercept("GET", "**/house/current", (req) => {
    req.reply({ statusCode: 200, body: houseDeleted ? null : houseWithTwoMembers });
  });
  cy.intercept("DELETE", "**/house/current", (req) => {
    houseDeleted = true;
    req.reply({ statusCode: 204 });
  }).as("deleteHouse");
});

Given("leaving the household will succeed", () => {
  cy.intercept("POST", "**/house/leave", { statusCode: 204 }).as("leaveHouse");
});

When("I click {string} for the member {string}", (action: string, member: string) => {
  cy.contains("li", member).contains("button", action).click();
});

Then("the household rename request should have been made with name {string}", (name: string) => {
  cy.wait("@renameHouse").its("request.body").should("deep.equal", { name });
});

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

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

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