import { describe, expect, it } from "vitest";
import {
  getBillableMemberCount,
  getOrganizationOwner,
  getTrialWindow,
  parseTrialRolloutDate,
} from "../../helpers/billing.js";

describe("billing helpers", () => {
  it("falls back to default rollout date when env value is missing", () => {
    const rolloutAt = parseTrialRolloutDate(undefined);
    expect(rolloutAt?.toISOString()).toBe("2026-03-08T00:00:00.000Z");
  });

  it("falls back to default rollout date when env value is invalid", () => {
    const rolloutAt = parseTrialRolloutDate("not-a-date");
    expect(rolloutAt?.toISOString()).toBe("2026-03-08T00:00:00.000Z");
  });

  it("uses configured rollout date when env value is valid", () => {
    const rolloutAt = parseTrialRolloutDate("2026-03-10T00:00:00.000Z");
    expect(rolloutAt?.toISOString()).toBe("2026-03-10T00:00:00.000Z");
  });

  it("returns the earliest organization member as billing owner", () => {
    const owner = getOrganizationOwner([
      {
        id: "owner-user",
        created_at: "2026-01-01T10:00:00.000Z",
        is_temporary: false,
        plan: "annual",
      },
      {
        id: "late-user",
        created_at: "2026-01-02T10:00:00.000Z",
        is_temporary: false,
        plan: "solo",
      },
    ]);

    expect(owner?.id).toBe("owner-user");
  });

  it("excludes temporary users from billable seat count", () => {
    const count = getBillableMemberCount([
      {
        id: "user-1",
        created_at: "2026-01-01T10:00:00.000Z",
        is_temporary: false,
        plan: "solo",
      },
      {
        id: "temp-1",
        created_at: "2026-01-02T10:00:00.000Z",
        is_temporary: true,
        plan: "solo",
      },
      {
        id: "user-2",
        created_at: "2026-01-03T10:00:00.000Z",
        is_temporary: null,
        plan: "team",
      },
    ]);

    expect(count).toBe(2);
  });

  it("uses rollout date as trial start for older organizations", () => {
    const result = getTrialWindow({
      ownerCreatedAt: new Date("2025-12-01T00:00:00.000Z"),
      now: new Date("2026-03-10T00:00:00.000Z"),
      trialDays: 14,
      rolloutAt: new Date("2026-03-08T00:00:00.000Z"),
    });

    expect(result.trialStartDate.toISOString()).toBe("2026-03-08T00:00:00.000Z");
    expect(result.trialEndDate.toISOString()).toBe("2026-03-22T00:00:00.000Z");
    expect(result.isTrialExpired).toBe(false);
  });

  it("uses owner creation date as trial start for new organizations", () => {
    const result = getTrialWindow({
      ownerCreatedAt: new Date("2026-03-12T00:00:00.000Z"),
      now: new Date("2026-03-28T00:00:00.000Z"),
      trialDays: 14,
      rolloutAt: new Date("2026-03-08T00:00:00.000Z"),
    });

    expect(result.trialStartDate.toISOString()).toBe("2026-03-12T00:00:00.000Z");
    expect(result.trialEndDate.toISOString()).toBe("2026-03-26T00:00:00.000Z");
    expect(result.isTrialExpired).toBe(true);
  });
});
