import { describe, expect, it } from "vitest";
import {
  mapAppleProductToPlan,
  normalizeAppleSubscriptionStatus,
  toAppleBillingCandidate,
  type AppleBillingCandidate,
} from "../../helpers/appleBilling.js";

describe("apple billing helpers", () => {
  const productConfig = {
    annualProductId: "annual_ios",
    soloProductId: "solo_ios_monthly",
  };

  it("maps the configured solo product id to the solo billing plan", () => {
    expect(mapAppleProductToPlan("solo_ios_monthly", productConfig)).toBe("solo");
  });

  it("maps the configured annual product id to the annual billing plan", () => {
    expect(mapAppleProductToPlan("annual_ios", productConfig)).toBe("annual");
  });

  it("returns null for unmapped products", () => {
    expect(mapAppleProductToPlan("team_ios_monthly", productConfig)).toBeNull();
  });

  it("normalizes expiration-like events to expired", () => {
    expect(normalizeAppleSubscriptionStatus("EXPIRATION", false)).toBe("expired");
    expect(normalizeAppleSubscriptionStatus("CANCELLATION", true)).toBe("canceled");
  });

  it("treats initial purchases as active until further lifecycle changes arrive", () => {
    expect(normalizeAppleSubscriptionStatus("INITIAL_PURCHASE", false)).toBe("active");
    expect(normalizeAppleSubscriptionStatus("RENEWAL", false)).toBe("active");
  });

  it("always shapes Apple billing candidates with quantity one", () => {
    const candidate = toAppleBillingCandidate({
      currentPeriodEnd: "2026-06-01T00:00:00.000Z",
      plan: "annual",
      status: "active",
    }) as AppleBillingCandidate;

    expect(candidate).toMatchObject({
      plan: "annual",
      quantity: 1,
      status: "active",
    });
    expect(candidate.currentPeriodEnd).toBe(Date.parse("2026-06-01T00:00:00.000Z") / 1000);
  });
});
