/**
 * Live Tracking — Measure approval drawer (Works tab)
 *
 * Verifies the approver flow for approving/unapproving proposed measures
 * directly from the Works tab of the PropertyDetailDrawer:
 *   1. The approver opens the Works tab and sees measure chips.
 *   2. The approver toggles a measure, clicks "Review & Save".
 *   3. The ApprovalConfirmDialog appears — the user types "approve".
 *   4. POST fires to /api/portfolio/*/approvals with the correct payload.
 *
 * Mirrors the same structure as `pibi-measures.cy.js`.
 * Uses `cy.intercept` to observe the API call without a real CRM round-trip.
 */

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

describe("Measure approval drawer — Works tab approver flow", function () {
  before(function () {
    if (!PORTFOLIO_SLUG) {
      cy.log(
        "LIVE_PORTFOLIO_SLUG env var not set — skipping live tracking specs",
      );
      this.skip();
    }
  });

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

    // Open a property row from the Measures table to get the detail drawer.
    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");

    // The drawer opens on the Works tab from a Measures row click — verify.
    cy.get("[data-testid=drawer-tab-panel-works]").should("be.visible");
    cy.get("[data-testid=drawer-section-measures]").should("exist");
  }

  it("fetches approved measures and shows chips in the Works tab for approvers", () => {
    // Stub the GET so we control the initial state.
    cy.intercept("GET", `/api/portfolio/*/pibi-measures*`, {
      body: {
        pibiMeasures: [],
        approvedMeasures: ["ASHP", "Solar PV"],
        instructedMeasures: [],
      },
    }).as("getMeasures");

    openDrawerAtWorksTab();

    cy.wait("@getMeasures");

    // Chip container should be visible.
    cy.get("[data-testid=measure-approval-chips]").should("be.visible");

    // ASHP and Solar PV should be shown as approved (checked).
    cy.get("[data-testid=measure-approval-checkbox-ASHP]").should("be.checked");
    cy.get("[data-testid='measure-approval-checkbox-Solar PV']").should(
      "be.checked",
    );
  });

  it("lets an approver toggle a measure and POST the approval change", () => {
    // Stub GET to return ASHP as already approved.
    cy.intercept("GET", `/api/portfolio/*/pibi-measures*`, {
      body: {
        pibiMeasures: [],
        approvedMeasures: ["ASHP"],
        instructedMeasures: [],
      },
    }).as("getMeasures");

    // Intercept the POST so we can assert the payload.
    cy.intercept("POST", `/api/portfolio/*/approvals`, {
      body: { success: true },
    }).as("postApprovals");

    openDrawerAtWorksTab();

    cy.wait("@getMeasures");

    cy.get("[data-testid=measure-approval-chips]").should("be.visible");

    // ASHP should start approved.
    cy.get("[data-testid=measure-approval-checkbox-ASHP]").should("be.checked");

    // Toggle ASHP off (unapprove it).
    cy.get("[data-testid=measure-approval-chip-ASHP]").click();
    cy.get("[data-testid=measure-approval-checkbox-ASHP]").should(
      "not.be.checked",
    );

    // "Review & Save" button should now be active.
    cy.get("[data-testid=measure-approval-save]").should("not.be.disabled");
    cy.get("[data-testid=measure-approval-save]").click();

    // ApprovalConfirmDialog should be visible — type the confirm word.
    cy.contains("Confirm approval changes").should("be.visible");
    cy.get("input[placeholder*=\"approve\"]").type("approve");
    cy.contains("button", "Confirm").click();

    // Wait for the POST and assert the payload.
    cy.wait("@postApprovals").then((intercepted) => {
      expect(intercepted.request.body).to.have.property("changes");
      const changes = intercepted.request.body.changes;
      // Should contain one change: ASHP unapproved.
      const ashpChange = changes.find((c) => c.measureName === "ASHP");
      expect(ashpChange).to.exist;
      expect(ashpChange.approved).to.equal(false);
    });

    // No error banner visible.
    cy.get("[data-testid=measure-approval-error]").should("not.exist");
  });

  it("lets an approver approve a new measure and POST with correct payload", () => {
    // Stub GET — no measures approved yet.
    cy.intercept("GET", `/api/portfolio/*/pibi-measures*`, {
      body: {
        pibiMeasures: [],
        approvedMeasures: [],
        instructedMeasures: [],
      },
    }).as("getMeasures");

    // Intercept POST.
    cy.intercept("POST", `/api/portfolio/*/approvals`, {
      body: { success: true },
    }).as("postApprovals");

    openDrawerAtWorksTab();

    cy.wait("@getMeasures");

    cy.get("[data-testid=measure-approval-chips]").should("be.visible");

    // Click the first chip to approve it.
    cy.get("[data-testid=measure-approval-chips]")
      .find("label")
      .first()
      .click();

    // Save button should be active.
    cy.get("[data-testid=measure-approval-save]").should("not.be.disabled");
    cy.get("[data-testid=measure-approval-save]").click();

    // Confirm dialog — type the word.
    cy.contains("Confirm approval changes").should("be.visible");
    cy.get("input[placeholder*=\"approve\"]").type("approve");
    cy.contains("button", "Confirm").click();

    cy.wait("@postApprovals").then((intercepted) => {
      expect(intercepted.request.body).to.have.property("changes");
      const changes = intercepted.request.body.changes;
      // Should have at least one approval.
      expect(changes.length).to.be.greaterThan(0);
      expect(changes[0]).to.have.property("approved", true);
      expect(changes[0]).to.have.property("hubspotDealId");
    });

    // No error banner.
    cy.get("[data-testid=measure-approval-error]").should("not.exist");
  });
});
