import { getKeyValueStore } from "../data/index.js";
import { ok } from "../is.js";
const STORE_NAME = "syncTag";
export function getSyncTagStore() {
    return getKeyValueStore(STORE_NAME, {
        counter: false
    });
}
export async function getSyncTagRegistrationState(tag) {
    const store = getSyncTagStore();
    const existing = await store.get(tag);
    ok(existing, "Expected to find registered sync tag");
    return existing.registrationState;
}
export async function setSyncTagRegistrationState(tag, registrationState) {
    const store = getSyncTagStore();
    const existing = await store.get(tag);
    ok(existing, "Expected to find registered sync tag");
    const next = {
        ...existing,
        registrationState,
        registrationStateAt: new Date().toISOString()
    };
    await store.set(tag, next);
    return next;
}
export async function deregisterSyncTag(tag) {
    const store = getSyncTagStore();
    await store.delete(tag);
}
export class DurableSyncManager {
    async register(tag) {
        const store = getSyncTagStore();
        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
        });
    }
    async getTags() {
        const store = getSyncTagStore();
        return await store.keys();
    }
    [Symbol.asyncIterator]() {
        const store = getSyncTagStore();
        return store[Symbol.asyncIterator]();
    }
}
export const sync = new DurableSyncManager();
//# sourceMappingURL=manager.js.map