<?php

namespace Fotogenic_AI;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

final class Auth_Refresh_Lock {
    private const OPTION_NAME = 'fotogenic_ai_auth_refresh_lock';
    private const STALE_AFTER_SECONDS = 90;
    private const MAX_WAIT_ATTEMPTS = 10;
    private const WAIT_USEC = 150000;

    public function acquire(): ?string {
        for ( $attempt = 0; $attempt < self::MAX_WAIT_ATTEMPTS; $attempt++ ) {
            $owner = Background_Lock::instance()->acquire_option( self::OPTION_NAME, self::STALE_AFTER_SECONDS );
            if ( false !== $owner ) {
                return $owner;
            }

            usleep( self::WAIT_USEC );
        }

        return null;
    }

    public function release( string $owner ): void {
        if ( '' === $owner ) {
            return;
        }

        Background_Lock::instance()->release_option( self::OPTION_NAME, $owner );
    }
}
