<?php

use PHPUnit\Framework\TestCase;
use SHServ\Entities\Area;

class AreaPlacingTest extends TestCase {
	private function create_areas_table(): void {
		app() -> thin_builder -> query("CREATE TABLE areas (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			alias VARCHAR(255),
			display_name VARCHAR(255),
			type VARCHAR(50),
			parent_id INTEGER DEFAULT 0,
			schema TEXT,
			create_at DATETIME,
			update_at DATETIME
		)");
	}

	private function drop_areas_table(): void {
		app() -> thin_builder -> query("DROP TABLE IF EXISTS areas");
	}

	protected function setUp(): void {
		$this -> create_areas_table();
	}

	protected function tearDown(): void {
		$this -> drop_areas_table();
	}

	public function test_place_in_area_updates_parent_id(): void {
		$tb = app() -> thin_builder;
		$tb -> insert('areas', [
			'alias' => 'parent',
			'display_name' => 'Parent',
			'type' => 'room',
			'parent_id' => 0,
			'schema' => '',
			'create_at' => '2024-01-01 10:00:00',
			'update_at' => '2024-01-01 10:00:00',
		]);
		$tb -> insert('areas', [
			'alias' => 'child',
			'display_name' => 'Child',
			'type' => 'room',
			'parent_id' => 0,
			'schema' => '',
			'create_at' => '2024-01-01 10:00:00',
			'update_at' => '2024-01-01 10:00:00',
		]);

		$child = new Area(2);
		$parent = new Area(1);

		$result = $child -> place_in_area($parent);
		$this -> assertTrue($result);

		$rows = $tb -> select('areas', ['parent_id'], [['id', '=', 2]]);
		$this -> assertEquals(1, (int) $rows[0]['parent_id']);
	}

	public function test_place_in_area_by_id_updates_parent_id(): void {
		$tb = app() -> thin_builder;
		$tb -> insert('areas', [
			'alias' => 'child2',
			'display_name' => 'Child 2',
			'type' => 'room',
			'parent_id' => 0,
			'schema' => '',
			'create_at' => '2024-01-01 10:00:00',
			'update_at' => '2024-01-01 10:00:00',
		]);

		$child = new Area(1);
		$result = $child -> place_in_area_id(99);
		$this -> assertTrue($result);

		$rows = $tb -> select('areas', ['parent_id'], [['id', '=', 1]]);
		$this -> assertEquals(99, (int) $rows[0]['parent_id']);
	}
}
