import { VacationType } from "@capakraken/db";
import { describe, expect, it } from "vitest";
import {
  buildTimelineAbsenceDays,
  loadTimelineCalculationRules,
} from "../router/timeline-cost-load-support.js";

describe("timeline cost load support", () => {
  it("falls back to default calculation rules when the optional model is unavailable", async () => {
    const rules = await loadTimelineCalculationRules({
      vacation: {
        findMany: async () => [],
      },
    } as never);

    expect(rules.length).toBeGreaterThan(0);
  });

  it("expands approved vacations, sickness, and public holidays into absence days", async () => {
    const result = await buildTimelineAbsenceDays({
      vacation: {
        findMany: async () => [
          {
            startDate: new Date("2026-04-03T00:00:00.000Z"),
            endDate: new Date("2026-04-04T00:00:00.000Z"),
            type: VacationType.VACATION,
            isHalfDay: false,
          },
          {
            startDate: new Date("2026-04-05T00:00:00.000Z"),
            endDate: new Date("2026-04-05T00:00:00.000Z"),
            type: VacationType.SICK,
            isHalfDay: true,
          },
          {
            startDate: new Date("2026-04-06T00:00:00.000Z"),
            endDate: new Date("2026-04-06T00:00:00.000Z"),
            type: VacationType.PUBLIC_HOLIDAY,
            isHalfDay: false,
          },
        ],
      },
    } as never, "resource_1", new Date("2026-04-01T00:00:00.000Z"), new Date("2026-04-10T00:00:00.000Z"));

    expect(result.absenceDays).toEqual([
      {
        date: new Date("2026-04-03T00:00:00.000Z"),
        type: "VACATION",
      },
      {
        date: new Date("2026-04-04T00:00:00.000Z"),
        type: "VACATION",
      },
      {
        date: new Date("2026-04-05T00:00:00.000Z"),
        type: "SICK",
        isHalfDay: true,
      },
      {
        date: new Date("2026-04-06T00:00:00.000Z"),
        type: "PUBLIC_HOLIDAY",
      },
    ]);
    expect(result.legacyVacationDates).toEqual([
      new Date("2026-04-03T00:00:00.000Z"),
      new Date("2026-04-04T00:00:00.000Z"),
    ]);
  });

  it("treats missing optional vacation tables as no absences", async () => {
    const result = await buildTimelineAbsenceDays({
      vacation: {
        findMany: async () => {
          throw {
            code: "P2021",
            message: "The table `vacations` does not exist.",
            meta: { table: "vacations" },
          };
        },
      },
    } as never, "resource_1", new Date("2026-04-01T00:00:00.000Z"), new Date("2026-04-10T00:00:00.000Z"));

    expect(result).toEqual({
      absenceDays: [],
      legacyVacationDates: [],
    });
  });
});
