/**
 * Live Tracking — Survey request flow
 *
 * Verifies the client-facing "Request Survey" flow in the Survey & Admin tab:
 *   1. User opens a property and navigates to Survey & Admin tab.
 *   2. User fills in a free-text reason and submits the survey request.
 *   3. The POST hits /api/portfolio/[id]/survey-requests.
 *   4. The drawer reflects the pending request (badge shown).
 *   5. On reload the pending request is still visible.
 *
 * Uses cy.intercept so the HubSpot side-effect is observable without a live
 * CRM round-trip.
 */

const PORTFOLIO_SLUG = Cypress.env("LIVE_PORTFOLIO_SLUG");
const TARGET_DEAL_NAME = Cypress.env("LIVE_SURVEY_REQUEST_DEAL_NAME");

const SURVEY_NOTES = "Please arrange a full retrofit assessment — tenant has moved in.";

describe("Survey request — write user flow", function () {
  before(function () {
    if (!PORTFOLIO_SLUG) {
      cy.log(
        "LIVE_PORTFOLIO_SLUG env var not set — skipping live tracking specs",
      );
      this.skip();
    }
  });

  function openDrawerAtSurveyAdmin() {
    cy.visit(`/portfolio/${PORTFOLIO_SLUG}/your-projects/live`);

    cy.contains("button, [role=tab]", "Measures").click();

    if (TARGET_DEAL_NAME) {
      cy.contains("[data-testid=measures-row]", TARGET_DEAL_NAME).click();
    } else {
      cy.get("[data-testid=measures-row]").first().click();
    }

    cy.get("[data-testid=property-detail-drawer]").should("be.visible");
    cy.get("[data-testid=drawer-tab-survey-admin]").click();
    cy.get("[data-testid=drawer-tab-panel-survey-admin]").should("be.visible");
  }

  it("shows the survey request form in the Survey & Admin tab", () => {
    openDrawerAtSurveyAdmin();

    cy.get("[data-testid=survey-request-form]").should("be.visible");
    cy.get("[data-testid=survey-request-notes]").should("be.visible");
    cy.get("[data-testid=survey-request-submit]").should("be.visible");
  });

  it("submits a survey request and shows a pending badge", () => {
    cy.intercept(
      "POST",
      `/api/portfolio/*/survey-requests`,
    ).as("createSurveyRequest");

    openDrawerAtSurveyAdmin();

    cy.get("[data-testid=survey-request-notes]").type(SURVEY_NOTES);
    cy.get("[data-testid=survey-request-submit]")
      .should("not.be.disabled")
      .click();

    cy.wait("@createSurveyRequest").then((intercepted) => {
      expect(intercepted.request.body).to.have.property("notes");
      expect(intercepted.response.statusCode).to.be.oneOf([200, 201]);
      expect(intercepted.response.body).to.have.property("ok", true);
    });

    // Pending badge appears after submission.
    cy.get("[data-testid=survey-request-pending-badge]").should("be.visible");
  });

  it("persists the pending request across a page reload", () => {
    openDrawerAtSurveyAdmin();

    // If a pending request exists it should be visible without submitting again.
    cy.get("[data-testid=survey-request-pending-badge]").should("be.visible");
  });
});
