import { describe, it, expect } from "vitest";
import { deriveEffectiveRemovalState, computeRemovalStatusByDeal } from "./removalState";

describe("deriveEffectiveRemovalState", () => {
  it("pending removal → pending_removal", () => {
    expect(deriveEffectiveRemovalState({ type: "removal", status: "pending" })).toBe("pending_removal");
  });

  it("pending re_addition → pending_re_addition", () => {
    expect(deriveEffectiveRemovalState({ type: "re_addition", status: "pending" })).toBe("pending_re_addition");
  });

  it("approved removal → removed", () => {
    expect(deriveEffectiveRemovalState({ type: "removal", status: "approved" })).toBe("removed");
  });

  it("declined re_addition → removed (re-addition refused means still out)", () => {
    expect(deriveEffectiveRemovalState({ type: "re_addition", status: "declined" })).toBe("removed");
  });

  it("approved re_addition → none (back in, no active removal state)", () => {
    expect(deriveEffectiveRemovalState({ type: "re_addition", status: "approved" })).toBe("none");
  });

  it("declined removal → none (removal refused, property stays in)", () => {
    expect(deriveEffectiveRemovalState({ type: "removal", status: "declined" })).toBe("none");
  });
});

describe("computeRemovalStatusByDeal", () => {
  it("returns empty map for no rows", () => {
    expect(computeRemovalStatusByDeal([])).toEqual({});
  });

  it("maps a single active removal row", () => {
    const rows = [{ hubspotDealId: "d1", type: "removal", status: "pending" }];
    expect(computeRemovalStatusByDeal(rows)).toEqual({ d1: "pending_removal" });
  });

  it("omits deals whose most recent state is none", () => {
    const rows = [{ hubspotDealId: "d1", type: "removal", status: "declined" }];
    expect(computeRemovalStatusByDeal(rows)).toEqual({});
  });

  it("deduplicates by deal — first row wins (most recent, caller provides DESC order)", () => {
    const rows = [
      { hubspotDealId: "d1", type: "removal", status: "approved" },  // most recent
      { hubspotDealId: "d1", type: "removal", status: "pending" },   // older, ignored
    ];
    expect(computeRemovalStatusByDeal(rows)).toEqual({ d1: "removed" });
  });

  it("handles multiple deals independently", () => {
    const rows = [
      { hubspotDealId: "d1", type: "removal", status: "pending" },
      { hubspotDealId: "d2", type: "re_addition", status: "pending" },
      { hubspotDealId: "d3", type: "re_addition", status: "approved" },
    ];
    expect(computeRemovalStatusByDeal(rows)).toEqual({
      d1: "pending_removal",
      d2: "pending_re_addition",
    });
  });
});
