<?php

namespace Velis\Test\Repository\QuickReport;

use PHPUnit\Framework\TestCase;
use Velis\App;
use Velis\Db\Db;
use Velis\QuickReport\Category;
use Velis\Repository\QuickReport\CategoryRepository;
use Velis\User;

/**
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 */
class CategoryRepositoryTest extends TestCase
{
    /**
     * @var CategoryRepository
     */
    private $repository;

    protected function setUp(): void
    {
        /** @var Db $db */
        $db = App::$di['db'];
        $this->repository = $db->getRepository(Category::class);
    }

    /**
     * @param User $user
     * @param int $expectedCategoryId
     *
     * @dataProvider provideTestDataForFindByUserMethod
     */
    public function testFindByUser(User $user, int $expectedCategoryId)
    {
        $categories = $this->repository->findByUser($user);

        $this->assertNotEmpty($categories);

        $isCategoryFound = false;

        foreach ($categories as $category) {
            $this->assertInstanceOf(Category::class, $category);

            if ($category->id() === $expectedCategoryId) {
                $isCategoryFound = true;
                break;
            }
        }

        $this->assertTrue($isCategoryFound);
    }

    public function provideTestDataForFindByUserMethod()
    {
        /** @var Db $db */
        $db = App::$di['db'];

        $userCategoryRow = $db->getRow('
            SELECT cu.user_id, cu.quick_report_category_id
            FROM app.quick_report_category_user_tab cu
            LIMIT 1
        ');

        $user = new User([
            'user_id' => $userCategoryRow['user_id'],
        ]);
        $userCategoryId = $userCategoryRow['quick_report_category_id'];

        $roleCategoryRow = $db->getRow('
            SELECT cr.quick_report_category_id, ur.user_id
            FROM
                app.quick_report_category_role_tab cr
                JOIN acl.user_role_tab ur USING (role_id)
            LIMIT 1
        ');

        $userWithRole = new User([
            'user_id' => $roleCategoryRow['user_id'],
        ]);
        $roleCategoryId = $roleCategoryRow['quick_report_category_id'];

        return [
            [$user, $userCategoryId],
            [$userWithRole, $roleCategoryId],
        ];
    }
}
