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

// Shared across household-settings.feature (dedicated create/join scenarios)
// and onboarding.feature (household step of the wizard) — both need to mock
// the create/join mutations and their up-to-date `GET /house/current`
// follow-up the same way.

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

// The page reloads `GET /house/current` right after each mutation below
// succeeds — these intercepts need to answer differently before/after that
// follow-up GET, hence a shared mutable flag rather than a single static
// `cy.intercept` (a later static one would just win for every request,
// including the initial page load).

Given("creating a household will succeed", () => {
  const createdHouse = {
    id: 1,
    name: "Chez Alice",
    adminId: 1,
    inviteCode: "ABCD2345",
    members: [{ id: 1, firstName: "Alice", lastName: "Martin" }],
  };
  let created = false;
  cy.intercept("GET", "**/house/current", (req) => {
    req.reply({ statusCode: 200, body: created ? createdHouse : null });
  });
  cy.intercept("POST", "**/house", (req) => {
    created = true;
    req.reply({ statusCode: 201, body: createdHouse });
  }).as("createHouse");
});

Given("joining a household will succeed", () => {
  let joined = false;
  cy.intercept("GET", "**/house/current", (req) => {
    req.reply({ statusCode: 200, body: joined ? houseWithTwoMembers : null });
  });
  cy.intercept("POST", "**/house/join", (req) => {
    joined = true;
    req.reply({ statusCode: 200, body: houseWithTwoMembers });
  }).as("joinHouse");
});

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

Then(
  "the household join request should have been made with invite code {string}",
  (code: string) => {
    cy.wait("@joinHouse").its("request.body").should("deep.equal", { inviteCode: code });
  },
);

// Shared between onboarding.feature's sources step and household-settings.feature's
// sources section — both read/write the same `/house/current/sources` endpoint.

Given("the household's enabled sources are empty", () => {
  cy.intercept("GET", "**/house/current/sources", { statusCode: 200, body: [] });
});

Given("saving the source selection will succeed", () => {
  cy.intercept("PATCH", "**/house/current/sources", (req) => {
    req.reply({ statusCode: 200, body: req.body.sourceIds });
  }).as("updateSources");
});

Then(
  "the source selection update request should have been made with source id {int}",
  (id: number) => {
    cy.wait("@updateSources")
      .its("request.body")
      .should("deep.equal", { sourceIds: [id] });
  },
);
