export class LockManager {
  private static mutex: Promise<void> = Promise.resolve();

  static async withMutex<T>(fn: () => Promise<T>): Promise<T> {
    const prev = LockManager.mutex;
    let release: () => void = () => {};
    LockManager.mutex = new Promise<void>((r) => { release = r; });
    try {
      await prev;
      return await fn();
    } finally {
      release();
    }
  }

  static async withWebLock<T>(lockName: string, fn: () => Promise<T>): Promise<T> {
    if (typeof navigator !== 'undefined' && navigator.locks) {
      return new Promise((resolve, reject) => {
        navigator.locks.request(lockName, { mode: 'exclusive' }, async (lock) => {
          if (!lock) {
            return reject(new Error('无法获取跨标签页锁'));
          }
          try {
            const result = await fn();
            resolve(result);
          } catch (e) {
            reject(e);
          }
        });
      });
    }
    return fn();
  }
}