package app.mealsmadeeasy.api.job;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.Optional;
import java.util.UUID;

public interface JobRepository extends JpaRepository<Job, UUID> {

    @Query(value = """
        WITH cte AS (
            SELECT id FROM job WHERE state = 'QUEUED' AND run_after <= now() ORDER BY run_after, created
            FOR UPDATE SKIP LOCKED LIMIT 1
        )
        UPDATE job j
        SET state = 'RUNNING',
            locked_by = ?1,
            locked_at = now(),
            modified = now()
        FROM cte
        WHERE j.id = cte.id
        RETURNING j.*
    """, nativeQuery = true)
    Optional<Job> claimNext(String lockedBy);

}
