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

declare(strict_types=1);

use BitBadger\PDODocument\{Custom, Delete, Document, DocumentException, Field, FieldMatch, Find};
use Test\Integration\{ArrayDocument, TestDocument};
use Test\Integration\SQLite\ThrowawayDb;

pest()->group('integration', 'sqlite');

describe('::all()', function () {
    test('retrieves data', function () {
        $docs = Find::all(ThrowawayDb::TABLE, TestDocument::class);
        expect($docs)->not->toBeNull();
        $count = 0;
        foreach ($docs->items as $ignored) $count++;
        expect($count)->toBe(5);
    });
    test('sorts data ascending', function () {
        $docs = Find::all(ThrowawayDb::TABLE, TestDocument::class, [Field::named('id')]);
        expect($docs)->not->toBeNull()
            ->and(iterator_to_array($docs->map(fn ($it) => $it->id), false))
            ->toBe(['five', 'four', 'one', 'three', 'two']);
    });
    test('sorts data descending', function () {
        $docs = Find::all(ThrowawayDb::TABLE, TestDocument::class, [Field::named('id DESC')]);
        expect($docs)->not->toBeNull()
            ->and(iterator_to_array($docs->map(fn ($it) => $it->id), false))
            ->toBe(['two', 'three', 'one', 'four', 'five']);
    });
    test('sorts data numerically', function () {
        $docs = Find::all(ThrowawayDb::TABLE, TestDocument::class,
            [Field::named('sub.foo NULLS LAST'), Field::named('n:num_value')]);
        expect($docs)->not->toBeNull()
            ->and(iterator_to_array($docs->map(fn ($it) => $it->id), false))
            ->toBe(['two', 'four', 'one', 'three', 'five']);
    });
    test('returns an empty list when no data exists', function () {
        Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
        expect(Find::all(ThrowawayDb::TABLE, TestDocument::class))
            ->not->toBeNull()->hasItems->toBeFalse();
    });
});

describe('::byId()', function () {
    test('returns a document when it exists', function () {
        $doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
        expect($doc)->isSome->toBeTrue()->and($doc->value)->id->toBe('two');
    });
    test('returns a document with a numeric ID', function () {
        Document::insert(ThrowawayDb::TABLE, ['id' => 18, 'value' => 'howdy']);
        $doc = Find::byId(ThrowawayDb::TABLE, 18, TestDocument::class);
        expect($doc)->isSome->toBeTrue()->and($doc->value)->id->toBe('18');
    });
    test('returns None when no document exists', function () {
        expect(Find::byId(ThrowawayDb::TABLE, 'seventy-five', TestDocument::class))->isNone->toBeTrue();
    });
});

describe('::byFields()', function () {
    test('returns matching documents', function () {
        $docs = Find::byFields(ThrowawayDb::TABLE, [Field::in('value', ['blue', 'purple']), Field::exists('sub')],
            TestDocument::class, FieldMatch::All);
        expect($docs)->not->toBeNull();
        $count = 0;
        foreach ($docs->items as $ignored) $count++;
        expect($count)->toBe(1);
    });
    test('returns ordered matching documents', function () {
        $docs = Find::byFields(ThrowawayDb::TABLE, [Field::equal('value', 'purple')], TestDocument::class,
            FieldMatch::All, [Field::named('id')]);
        expect($docs)->not->toBeNull()
            ->and(iterator_to_array($docs->map(fn ($it) => $it->id), false))->toBe(['five', 'four']);
    });
    test('returns documents matching numeric IN clause', function () {
        $docs = Find::byFields(ThrowawayDb::TABLE, [Field::in('num_value', [2, 4, 6, 8])], TestDocument::class);
        expect($docs)->not->toBeNull();
        $count = 0;
        foreach ($docs->items as $ignored) $count++;
        expect($count)->toBe(1);
    });
    test('returns empty list when no documents match', function () {
        expect(Find::byFields(ThrowawayDb::TABLE, [Field::greater('num_value', 100)], TestDocument::class))
            ->not->toBeNull()->hasItems->toBeFalse();
    });
    test('returns matching documents for inArray comparison', function () {
        Delete::byFields(ThrowawayDb::TABLE, [Field::notExists('absentField')]);
        foreach (ArrayDocument::testDocuments() as $doc) Document::insert(ThrowawayDb::TABLE, $doc);
        $docs = Find::byFields(ThrowawayDb::TABLE, [Field::inArray('values', ThrowawayDb::TABLE, ['c'])],
            ArrayDocument::class);
        expect($docs)->not->toBeNull();
        $count = 0;
        foreach ($docs->items as $ignored) $count++;
        expect($count)->toBe(2);
    });
    test('returns empty list when no documents match inArray comparison', function () {
        Delete::byFields(ThrowawayDb::TABLE, [Field::notExists('absentField')]);
        foreach (ArrayDocument::testDocuments() as $doc) Document::insert(ThrowawayDb::TABLE, $doc);
        expect(Find::byFields(ThrowawayDb::TABLE, [Field::inArray('values', ThrowawayDb::TABLE, ['j'])],
                ArrayDocument::class))
            ->not->toBeNull()->hasItems->toBeFalse();
    });
});

describe('::byContains()', function () {
    test('throws an exception', function () {
        expect(fn () => Find::byContains('', [], TestDocument::class))->toThrow(DocumentException::class);
    });
});

describe('::byJsonPath()', function () {
    test('throws an exception', function () {
        expect(fn () => Find::byJsonPath('', '', TestDocument::class))->toThrow(DocumentException::class);
    });
});

describe('::firstByFields()', function () {
    test('returns a matching document', function () {
        $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'another')], TestDocument::class);
        expect($doc)->isSome->toBeTrue()->and($doc->value)->id->toBe('two');
    });
    test('returns one of several matching documents', function () {
        $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('sub.foo', 'green')], TestDocument::class);
        expect($doc)->isSome->toBeTrue()->and(['two', 'four'])->toContain($doc->value->id);
    });
    test('returns first of ordered matching documents', function () {
        $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('sub.foo', 'green')], TestDocument::class,
            orderBy: [Field::named('n:num_value DESC')]);
        expect($doc)->isSome->toBeTrue()->and($doc->value)->id->toBe('four');
    });
    test('returns None when no documents match', function () {
        expect(Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'absent')], TestDocument::class))
            ->isNone->toBeTrue();
    });
});

describe('::firstByContains()', function () {
    test('throws an exception', function () {
        expect(fn () => Find::firstByContains('', [], TestDocument::class))->toThrow(DocumentException::class);
    });
});

describe('::firstByJsonPath()', function () {
    test('throws an exception', function () {
        expect(fn () => Find::firstByJsonPath('', '', TestDocument::class))->toThrow(DocumentException::class);
    });
});