<?php

use PHPUnit\Framework\TestCase;
use SHServ\Models\Devices;

class DevicesTest extends TestCase {
	protected $tb;

	protected function setUp(): void {
		$this -> tb = app() -> thin_builder;
		$this -> tb -> query("CREATE TABLE devices (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			area_id INTEGER DEFAULT 0,
			alias TEXT,
			name TEXT,
			device_type TEXT,
			device_ip TEXT,
			device_mac TEXT,
			device_hard_id TEXT,
			firmware_version TEXT,
			connection_status TEXT,
			status TEXT,
			description TEXT,
			last_contact TEXT,
			create_at TEXT,
			update_at TEXT
		)");
	}

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

	public function test_reconcile_updates_ip_and_restores_connection_status(): void {
		$this -> tb -> insert('devices', [
			'alias' => 'roaming',
			'name' => 'Roaming',
			'device_type' => 'relay',
			'device_ip' => '192.168.1.40',
			'device_hard_id' => 'hard_roam_001',
			'connection_status' => 'lost',
			'status' => 'active',
			'last_contact' => date('Y-m-d H:i:s', time() - 600),
			'create_at' => date('Y-m-d H:i:s'),
		]);

		$devices_model = new Devices();
		$result = $devices_model -> reconcile_scan_results([
			[
				'device_id' => 'hard_roam_001',
				'ip_address' => '192.168.1.99',
				'device_type' => 'relay',
			]
		]);

		$this -> assertSame(1, $result['updated']);
		$this -> assertSame(1, $result['restored']);

		$row = $this -> tb -> query("SELECT device_ip, connection_status FROM devices WHERE device_hard_id = 'hard_roam_001'") -> fetch(\PDO::FETCH_ASSOC);
		$this -> assertSame('192.168.1.99', $row['device_ip']);
		$this -> assertSame('active', $row['connection_status']);
	}

	public function test_reconcile_skips_unknown_devices(): void {
		$this -> tb -> insert('devices', [
			'alias' => 'known',
			'name' => 'Known',
			'device_type' => 'relay',
			'device_ip' => '192.168.1.10',
			'device_hard_id' => 'hard_known_001',
			'connection_status' => 'active',
			'status' => 'active',
			'last_contact' => date('Y-m-d H:i:s'),
			'create_at' => date('Y-m-d H:i:s'),
		]);

		$devices_model = new Devices();
		$result = $devices_model -> reconcile_scan_results([
			[
				'device_id' => 'hard_unknown_999',
				'ip_address' => '192.168.1.99',
				'device_type' => 'relay',
			]
		]);

		$this -> assertSame(0, $result['updated']);
		$this -> assertSame(0, $result['restored']);

		$row = $this -> tb -> query("SELECT device_ip, connection_status FROM devices WHERE device_hard_id = 'hard_known_001'") -> fetch(\PDO::FETCH_ASSOC);
		$this -> assertSame('192.168.1.10', $row['device_ip']);
		$this -> assertSame('active', $row['connection_status']);
	}
}
