import { parseSchedule, scheduleCron } from "./notification-schedule.service";

/**
 * The cadence editor's only sharp edge: a stored value compiles to a cron
 * expression that the scheduler installs verbatim. A malformed one either
 * throws at install time (taking the sweep down) or silently installs the
 * wrong cadence, so validation happens before anything is written.
 */

describe("scheduleCron", () => {
  it("compiles a daily schedule with no weekday filter", () => {
    expect(
      scheduleCron({ enabled: true, hour: 6, minute: 0, weekdays: [] }),
    ).toBe("0 6 * * *");
  });

  it("compiles the legacy Mon/Wed/Fri cadence, sorted and de-duplicated", () => {
    expect(
      scheduleCron({ enabled: true, hour: 7, minute: 30, weekdays: [5, 1, 3, 1] }),
    ).toBe("30 7 * * 1,3,5");
  });
});

describe("parseSchedule", () => {
  it("normalizes weekdays and coerces enabled to a boolean", () => {
    const parsed = parseSchedule({
      enabled: 1,
      hour: 6,
      minute: 0,
      weekdays: [3, 1, 3],
    });
    expect(parsed).toEqual({
      ok: true,
      value: { enabled: true, hour: 6, minute: 0, weekdays: [1, 3] },
    });
  });

  it("defaults a missing weekday list to every day", () => {
    const parsed = parseSchedule({ enabled: true, hour: 0, minute: 0 });
    expect(parsed.ok && parsed.value.weekdays).toEqual([]);
  });

  it.each([
    [{ enabled: true, hour: 24, minute: 0 }, "hora"],
    [{ enabled: true, hour: 6, minute: 60 }, "minutos"],
    [{ enabled: true, hour: 6, minute: 0, weekdays: [7] }, "días"],
    [{ enabled: true, hour: 6.5, minute: 0 }, "hora"],
  ])("rejects %p", (input, field) => {
    const parsed = parseSchedule(input);
    expect(parsed.ok).toBe(false);
    expect(!parsed.ok && parsed.error.toLowerCase()).toContain(field);
  });

  it("rejects a non-object", () => {
    expect(parseSchedule(null).ok).toBe(false);
  });
});
