import { virtual } from "../events/virtual/virtual.js";
import { listDurableEventIds } from "../data/durable-event/list-durable-event-ids.js";
import { getDurableEvent, setDurableEvent } from "../data/index.js";
import { isMatchingObjects } from "../is.js";
import { getPeriodicSyncSchedule } from "./schedule.js";
import { isScheduleRepeating } from "../events/schedule/update.js";
async function* generatePeriodicSyncVirtualEvents(manager) {
    const schedules = await getPeriodicSyncSchedule(manager);
    const type = "periodicsync";
    const existingTags = await listDurableEventIds({
        type
    });
    const tags = schedules.map(({ tag }) => tag);
    const tagsToDelete = existingTags.filter(tag => !tags.includes(tag));
    const { deleteDispatchEvent } = await import("../events/index.js");
    // console.log({ tagsToDelete, schedules, existingTags })
    for (const tag of tagsToDelete) {
        const existing = await getDurableEvent({
            type,
            durableEventId: tag
        });
        if (existing) {
            await deleteDispatchEvent(existing);
        }
    }
    for (const { tag, schedule } of schedules) {
        const event = {
            durableEventId: tag,
            type,
            tag,
            schedule,
            retain: isScheduleRepeating(schedule)
        };
        // Get existing so we are able to retain all event context data, like first created
        const existing = await getDurableEvent(event);
        const dispatch = await setDurableEvent({
            ...existing,
            ...event
        });
        yield {
            type: "dispatch",
            dispatch
        };
    }
}
export const removePeriodicSyncVirtualFunction = virtual(generatePeriodicSyncVirtualEvents);
export function isMatchingDurableEventSchedule(a, b) {
    return isMatchingObjects(a, b);
}
//# sourceMappingURL=virtual.js.map