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

declare(strict_types=1);

namespace Test\Integration\SQLite;

use BitBadger\PDODocument\{DocumentList, Query};
use BitBadger\PDODocument\Mapper\DocumentMapper;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
use Test\Integration\TestDocument;

/**
 * SQLite integration tests for the DocumentList class
 */
#[TestDox('DocumentList (SQLite integration)')]
class DocumentListTest extends TestCase
{
    /** @var string Database name for throwaway database */
    private string $dbName;

    protected function setUp(): void
    {
        parent::setUp();
        $this->dbName = ThrowawayDb::create();
    }

    protected function tearDown(): void
    {
        ThrowawayDb::destroy($this->dbName);
        parent::tearDown();
    }

    public function testCreateSucceeds(): void
    {
        $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
            new DocumentMapper(TestDocument::class));
        $this->assertNotNull($list, 'There should have been a document list created');
        $list = null;
    }

    public function testItems(): void
    {
        $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
            new DocumentMapper(TestDocument::class));
        $this->assertNotNull($list, 'There should have been a document list created');
        $count = 0;
        foreach ($list->items() as $item) {
            $this->assertContains($item->id, ['one', 'two', 'three', 'four', 'five'],
                'An unexpected document ID was returned');
            $count++;
        }
        $this->assertEquals(5, $count, 'There should have been 5 documents returned');
    }

    public function testHasItemsSucceedsWithEmptyResults(): void
    {
        $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'num_value' < 0", [],
            new DocumentMapper(TestDocument::class));
        $this->assertNotNull($list, 'There should have been a document list created');
        $this->assertFalse($list->hasItems(), 'There should be no items in the list');
    }

    public function testHasItemsSucceedsWithNonEmptyResults(): void
    {
        $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
            new DocumentMapper(TestDocument::class));
        $this->assertNotNull($list, 'There should have been a document list created');
        $this->assertTrue($list->hasItems(), 'There should be items in the list');
        foreach ($list->items() as $ignored) {
            $this->assertTrue($list->hasItems(), 'There should be items remaining in the list');
        }
        $this->assertFalse($list->hasItems(), 'There should be no remaining items in the list');
    }
}