<?php

declare(strict_types=1);

class Lock
{
    private PDO $pdo;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function acquire(string $jobName): bool
    {
        $st = $this->pdo->prepare("
            UPDATE cron_jobs
            SET
                is_running=1,
                started_at=NOW()
            WHERE
                name=?
            AND enabled=1
            AND (
                is_running=0
                OR started_at IS NULL
                OR started_at < DATE_SUB(NOW(),INTERVAL 10 MINUTE)
            )
        ");

        $st->execute([$jobName]);

        return $st->rowCount() > 0;
    }

    public function release(string $jobName): void
    {
        $st = $this->pdo->prepare("
            UPDATE cron_jobs
            SET
                is_running=0,
                started_at=NULL,
                last_run=NOW()
            WHERE name=?
        ");

        $st->execute([$jobName]);
    }
}