import { getKeyValueStore } from "../data/index.js";
import { ok } from "../is.js";
const STORE_NAME = "periodicSyncTag";
function getPeriodicSyncTagStore() {
    return getKeyValueStore(STORE_NAME, {
        counter: false
    });
}
export async function getPeriodicSyncTagRegistration(tag) {
    const store = getPeriodicSyncTagStore();
    const existing = await store.get(tag);
    ok(existing, "Expected to find registered periodic sync tag");
    return existing;
}
export async function getPeriodicSyncTagRegistrationState(tag) {
    const existing = await getPeriodicSyncTagRegistration(tag);
    return existing.registrationState;
}
export async function setPeriodicSyncTagRegistrationState(tag, registrationState) {
    const existing = await getPeriodicSyncTagRegistration(tag);
    const next = {
        ...existing,
        registrationState,
        registrationStateAt: new Date().toISOString()
    };
    const store = getPeriodicSyncTagStore();
    await store.set(tag, next);
    return next;
}
export async function deregisterPeriodicSyncTag(tag) {
    const store = getPeriodicSyncTagStore();
    await store.delete(tag);
}
export class DurablePeriodicSyncManager {
    async register(tag, options) {
        const store = getPeriodicSyncTagStore();
        const existing = await store.get(tag);
        const isFiring = existing?.registrationState === "firing";
        if (existing && !isFiring) {
            return;
        }
        let registrationState = "pending";
        if (isFiring) {
            registrationState = "reregisteredWhileFiring";
        }
        const registeredAt = new Date().toISOString();
        await store.set(tag, {
            tag,
            createdAt: existing?.createdAt || registeredAt,
            registeredAt,
            registrationState,
            registrationStateAt: registeredAt,
            ...options
        });
    }
    async getTags() {
        const store = getPeriodicSyncTagStore();
        return await store.keys();
    }
    async unregister(tag) {
        await deregisterPeriodicSyncTag(tag);
    }
}
export const periodicSync = new DurablePeriodicSyncManager();
//# sourceMappingURL=manager.js.map