# Copyright 2015 SUSE LLC
# SPDX-License-Identifier: GPL-2.0-or-later

package OpenQA::Schema::Result::JobNextPrevious;

## no critic (OpenQA::RedundantStrictWarning)
use Mojo::Base 'DBIx::Class::Core', -signatures;

use Moose;
extends 'OpenQA::Schema::Result::Jobs';

__PACKAGE__->table_class('DBIx::Class::ResultSource::View');

# For the time being this is necessary even for virtual views
__PACKAGE__->table('JobNextPrevious');
__PACKAGE__->add_columns(source => {data_type => 'text'});

# do not attempt to deploy() this view
__PACKAGE__->result_source_instance->is_virtual(1);

__PACKAGE__->result_source_instance->view_definition(
    <<~'END_SQL'
    WITH allofjobs AS(
        SELECT me.* FROM jobs me
            WHERE me.state=?
                AND me.result NOT IN (?, ?, ?, ?, ?, ?)
                AND me.DISTRI=? AND me.VERSION=? AND me.FLAVOR=? AND me.ARCH=?
                AND me.TEST=? AND me.MACHINE=?
    )
    ((SELECT *, 'l' AS source FROM jobs
        WHERE DISTRI=? AND VERSION=? AND FLAVOR=? AND ARCH=? AND TEST=? AND MACHINE=?
        ORDER BY ID DESC LIMIT 1)
    UNION (SELECT *, 'n' AS source FROM allofjobs WHERE id > ? ORDER BY ID ASC LIMIT ? + 1)
    UNION (SELECT *, 'p' AS source FROM allofjobs WHERE id < ? ORDER BY ID DESC LIMIT ? + 1)
    UNION (SELECT *, 'c' AS source FROM jobs WHERE id = ?)
    ORDER BY ID DESC)
    END_SQL
);

1;
