<?php

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

class UserEntityTest extends TestCase {
	protected $tb;

	protected function setUp(): void {
		$this -> tb = app() -> thin_builder;
		$this -> tb -> query("CREATE TABLE users (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			role TEXT,
			nickname TEXT,
			password TEXT,
			create_at TEXT,
			update_at TEXT
		)");
		$this -> tb -> query("CREATE TABLE profiles (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			uid INTEGER,
			first_name TEXT,
			mid_name TEXT,
			last_name TEXT,
			userpic TEXT,
			contacts TEXT,
			update_at TEXT,
			create_at TEXT
		)");
	}

	protected function tearDown(): void {
		$this -> tb -> query("DROP TABLE IF EXISTS users");
		$this -> tb -> query("DROP TABLE IF EXISTS profiles");
	}

	public function test_user_does_not_query_profile_on_construct(): void {
		$this -> tb -> insert('users', [
			'role' => 'admin',
			'nickname' => 'tester',
			'password' => 'secret',
			'create_at' => date('Y-m-d H:i:s'),
		]);

		// Constructing a User must not touch the profiles table.
		// If it did, the empty profiles table would not cause an error,
		// but the absence of eager-loading is proven by the next test.
		$user = new User(1);
		$this -> assertSame(1, $user -> id());
	}

	public function test_user_profile_lazy_loads(): void {
		$this -> tb -> insert('users', [
			'role' => 'admin',
			'nickname' => 'tester',
			'password' => 'secret',
			'create_at' => date('Y-m-d H:i:s'),
		]);
		$this -> tb -> insert('profiles', [
			'uid' => 1,
			'first_name' => 'Eugene',
			'last_name' => 'Sukhodolskiy',
			'create_at' => date('Y-m-d H:i:s'),
		]);

		$user = new User(1);
		$profile = $user -> profile();

		$this -> assertNotNull($profile);
		$this -> assertSame('Eugene', $profile -> first_name);
	}

	public function test_user_profile_returns_null_when_missing(): void {
		$this -> tb -> insert('users', [
			'role' => 'admin',
			'nickname' => 'tester',
			'password' => 'secret',
			'create_at' => date('Y-m-d H:i:s'),
		]);

		$user = new User(1);
		$this -> assertNull($user -> profile());
	}
}
