import { describe, expect, it } from "vitest";
import {
  buildAllocationWorkingDaySegments,
  isAllocationScheduledOnDate,
  toLocalDateKey,
} from "./timelineAvailability.js";
import type { TimelineAssignmentEntry } from "./TimelineContext.js";

function createAllocation(overrides?: Partial<TimelineAssignmentEntry>): TimelineAssignmentEntry {
  return {
    id: "alloc-1",
    resourceId: "resource-1",
    projectId: "project-1",
    startDate: new Date(2026, 2, 30),
    endDate: new Date(2026, 3, 6),
    hoursPerDay: 8,
    metadata: null,
    project: {
      id: "project-1",
      name: "Gelddruckmaschine",
      shortCode: "GDM",
      status: "ACTIVE",
      startDate: new Date(2026, 2, 30),
      endDate: new Date(2026, 3, 6),
      orderType: "CHARGEABLE",
    },
    resource: {
      id: "resource-1",
      displayName: "Peter Parker",
      eid: "E-001",
      chapter: "Delivery",
      lcrCents: 10000,
      availability: {
        sunday: 0,
        monday: 8,
        tuesday: 8,
        wednesday: 8,
        thursday: 8,
        friday: 8,
        saturday: 6,
      },
    },
    ...overrides,
  } as TimelineAssignmentEntry;
}

describe("timelineAvailability", () => {
  it("does not treat Saturday as scheduled unless includeSaturday is enabled", () => {
    const allocation = createAllocation();

    expect(isAllocationScheduledOnDate(allocation, new Date(2026, 3, 4))).toBe(false);
    expect(isAllocationScheduledOnDate(allocation, new Date(2026, 3, 6))).toBe(true);
  });

  it("supports Saturday working allocations when includeSaturday is enabled", () => {
    const allocation = createAllocation({
      metadata: { includeSaturday: true },
    });

    expect(isAllocationScheduledOnDate(allocation, new Date(2026, 3, 4))).toBe(true);
  });

  it("splits working spans at non-working weekend days", () => {
    const allocation = createAllocation();
    const segments = buildAllocationWorkingDaySegments(allocation);

    expect(segments).toEqual([
      { start: new Date(2026, 2, 30), end: new Date(2026, 3, 3) },
      { start: new Date(2026, 3, 6), end: new Date(2026, 3, 6) },
    ]);
  });

  it("formats local calendar days without shifting them through UTC serialization", () => {
    expect(toLocalDateKey(new Date(2026, 3, 6))).toBe("2026-04-06");
    expect(toLocalDateKey(new Date(2026, 3, 10))).toBe("2026-04-10");
  });
});
