<?php
/**
 * @author Daniel J. Summers <daniel@bitbadger.solutions>
 * @license MIT
 */

declare(strict_types=1);

use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode};
use BitBadger\PDODocument\Query\Exists;

pest()->group('unit');

afterEach(function () { Configuration::overrideMode(null); });

describe('::query()', function () {
    test('generates correct SQL', function () {
        Configuration::overrideMode(Mode::SQLite);
        expect(Exists::query('abc', 'def'))->toBe('SELECT EXISTS (SELECT 1 FROM abc WHERE def)');
    });
});

describe('::byId()', function () {
    test('generates correct SQL', function () {
        Configuration::overrideMode(Mode::SQLite);
        expect(Exists::byId('dox'))->toBe("SELECT EXISTS (SELECT 1 FROM dox WHERE data->>'id' = :id)");
    });
});

describe('::byFields()', function () {
    test('generates correct SQL', function () {
        Configuration::overrideMode(Mode::SQLite);
        expect(Exists::byFields('box', [Field::notEqual('status', 'occupied', ':status')]))
            ->toBe("SELECT EXISTS (SELECT 1 FROM box WHERE data->>'status' <> :status)");
    });
});

describe('::byContains()', function () {
    test('generates correct SQL [PostgreSQL]', function () {
        Configuration::overrideMode(Mode::PgSQL);
        expect(Exists::byContains('pocket'))->toBe('SELECT EXISTS (SELECT 1 FROM pocket WHERE data @> :criteria)');
    })->group('postgresql');
    test('throws an exception [SQLite]', function () {
        Configuration::overrideMode(Mode::SQLite);
        expect(fn () => Exists::byContains(''))->toThrow(DocumentException::class);
    })->group('sqlite');
});

describe('::byJsonPath()', function () {
    test('generates correct SQL [PostgreSQL]', function () {
        Configuration::overrideMode(Mode::PgSQL);
        expect(Exists::byJsonPath('lint'))
            ->toBe('SELECT EXISTS (SELECT 1 FROM lint WHERE jsonb_path_exists(data, :path::jsonpath))');
    })->group('postgresql');
    test('throws an exception [SQLite]', function () {
        Configuration::overrideMode(Mode::SQLite);
        expect(fn () => Exists::byJsonPath(''))->toThrow(DocumentException::class);
    })->group('sqlite');
});