<?php

namespace Test\Routes\Owner\{{ module }};

use App\DBRealTestSupport\TableCreation;
use App\DBRealTestSupport\TransactionSupported\TS{{ module }}Mother;
use App\DBRealTestSupport\TransactionSupported\Session\TSAdminSessionGenerator;
use App\DBRealTestSupport\TransactionSupported\Session\TSHistoryTableMother;
use App\Http\History\HistoryTables;
use App\Modules\{{ module }}\Domain\{{ module }};
use App\Modules\{{ module }}\Domain\{{ module }}Repository;
use App\Modules\{{ module }}\Domain\Id{{ module }};
use App\Modules\{{ module }}\Domain\Index{{ module }};
use App\Modules\History\Application\List\ListHistoryQuery;
use App\Modules\History\Application\List\ListHistoryResponses;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use Test\TestCase;
use Test\TransactionTrait;
use Test\TransactionSpyTrait;

class {{ module }}InsertControllerTest extends TestCase
{
    use TransactionTrait;
    use TransactionSpyTrait;

    private static $session;
    private static $token;
    private static $admin;
    private {{ module }}Repository $repository;
    private QueryBus $queryBus;

    public function init()
    {
        $this->clear();
        $this->repository = $this->app->make({{ module }}Repository::class);
        $this->queryBus   = $this->app->make(QueryBus::class);
        list(self::$session, self::$token, self::$admin) = TSAdminSessionGenerator::createAll();
        TSHistoryTableMother::insert(HistoryTables::{{ const }});
    }

    public function clear()
    {
        TSHistoryTableMother::clear();
        TableCreation::clearTables(
{{ clear }}
        );
    }

    public function testInsert()
    {
        $this->init();
        $built = TS{{ module }}Mother::random();
        $this->post('owner/{{ route }}', $built->toArray(), self::$token);
        $response = $this->decoded();

        /** @var {{ module }} $found */
        $found = $this->repository->find(new Index{{ module }}(new Id{{ module }}($response->data->id)));
        $this->check($built, $found);

        /** @var ListHistoryResponses $historyResponse */
        $historyResponse = $this->queryBus->ask(new ListHistoryQuery(
            date('Y-m-d', strtotime('-1 day')),
            date('Y-m-d', strtotime('+1 day')),
            HistoryTables::{{ const }},
            $found->id()->value(),
            'all',
            null,
            null
        ));

        $this->assertEquals(1, count($historyResponse->data()));
    }

    public function testInsertIsTransactional()
    {
        $this->init();
        $this->bindTransactionSpy();

        $built = TS{{ module }}Mother::random();
        $this->post('owner/{{ route }}', $built->toArray(), self::$token);

        $this->assertTransactionalSuccess();
    }

    public function check({{ module }} $built, {{ module }} $data)
    {
{{ checks }}
    }
}
