<?php

declare(strict_types=1);

namespace Apexl\Tests\Core\Infrastructure;

trait UsesTestEntities
{
    private ?string $testEntityTableName;
    private ?string $testRelatedEntityTableName;
    private ?string $testHasManyPivotTableName;
    private string $uniqId;

    private function createTestEntityTables(): void
    {
        $this->uniqId = uniqid();
        logger('query')->info(
            '--------------------------------------------------------------------------------------------------------------------'
        );
        logger('query')->info('STARTED ' . $this->name() . '__' . $this->uniqId);
        $this->testEntityTableName = "load_test_entity__$this->uniqId";
        TestEntity::$tableName = $this->testEntityTableName;

        $this->testRelatedEntityTableName = "load_test_related_entity__$this->uniqId";
        TestRelatedEntity::$tableName = $this->testRelatedEntityTableName;

        $this->testHasManyPivotTableName = "load_test_has_many_pivot__$this->uniqId";
        TestEntity::$hasManyPivotTableName = $this->testHasManyPivotTableName;

        self::$db->executeSql(
            <<<SQL
            create table `$this->testEntityTableName`
            (
                id int(11) unsigned auto_increment primary key,
                name varchar(256) not null,
                related_test_entity_id int(11) unsigned,
                unique index `idx_name` (`name`)
            )
            SQL
        );

        self::$db->executeSql(
            <<<SQL
            create table `$this->testRelatedEntityTableName`
            (
                id int(11) unsigned auto_increment primary key,
                name varchar(256) not null,
                test_entity_id int(11) unsigned,
                unique index `idx_name` (`name`)
            )
            SQL
        );

        self::$db->executeSql(
            <<<SQL
            create table `$this->testHasManyPivotTableName`
            (
                id int(11) unsigned auto_increment primary key,
                local_id int(11) unsigned not null,
                remote_id int(11) unsigned not null,
                weight int(11) not null default 0
            )
            SQL
        );
    }

    private function dropTestEntityTables(): void
    {
        logger('query')->info('FINISHED  ' . $this->uniqId);
        self::$db->executeSql("drop table `$this->testEntityTableName`");
        self::$db->executeSql("drop table `$this->testRelatedEntityTableName`");
        self::$db->executeSql("drop table `$this->testHasManyPivotTableName`");

        $this->testEntityTableName = null;
        TestEntity::$tableName = null;

        $this->testRelatedEntityTableName = null;
        TestRelatedEntity::$tableName = null;

        $this->testHasManyPivotTableName = null;
        TestEntity::$hasManyPivotTableName = null;

    }
}