<?php

namespace MintyPHP\Repository\Support;

use MintyPHP\DB;

class DatabaseSessionRepository implements DatabaseSessionRepositoryInterface
{
    public function acquireAdvisoryLock(string $lockName, int $timeoutSeconds = 0): bool
    {
        $lockName = trim($lockName);
        if ($lockName === '') {
            return false;
        }

        $timeoutSeconds = max(0, (int) $timeoutSeconds);
        $got = DB::selectValue(
            'select GET_LOCK(?, ?) as got_lock',
            $lockName,
            (string) $timeoutSeconds
        );

        return (int) $got === 1;
    }

    public function releaseAdvisoryLock(string $lockName): void
    {
        $lockName = trim($lockName);
        if ($lockName === '') {
            return;
        }

        DB::selectValue('select RELEASE_LOCK(?) as released_lock', $lockName);
    }

    public function beginTransaction(): void
    {
        DB::handle()->begin_transaction();
    }

    public function commitTransaction(): void
    {
        DB::handle()->commit();
    }

    public function rollbackTransaction(): void
    {
        DB::handle()->rollback();
    }
}
