<?php

use PHPUnit\Framework\TestCase;
use SHServ\Middleware\ControlScripts;

class ControlScriptsRegularTest extends TestCase {
	protected $tb;

	protected function setUp(): void {
		$this -> tb = app() -> thin_builder;
		$this -> tb -> query("CREATE TABLE scripts (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			area_id INTEGER DEFAULT 0,
			uniq_name TEXT,
			type TEXT,
			state TEXT,
			params_schema TEXT,
			create_at TEXT,
			update_at TEXT
		)");
		if(!isset(app() -> scripts_registry)) {
			app() -> scripts_registry = new \SHServ\Middleware\ScriptsRegistry();
		}
		ControlScripts::flush_statics();
	}

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

	public function test_run_regular_script_returns_false_when_alias_missing(): void {
		$this -> assertFalse(ControlScripts::run_regular_script('nonexistent'));
	}

	public function test_run_regular_script_returns_false_when_disabled(): void {
		app() -> scripts_registry -> regular['disabled'] = [
			'attributes' => ['alias' => 'disabled'],
			'code' => '',
			'script' => function() {}
		];

		$this -> tb -> insert('scripts', [
			'uniq_name' => 'disabled',
			'type' => 'regular',
			'state' => 'disabled',
			'create_at' => date('Y-m-d H:i:s'),
		]);

		$this -> assertFalse(ControlScripts::run_regular_script('disabled'));
	}

	public function test_run_regular_script_catches_exception(): void {
		app() -> scripts_registry -> regular['fail'] = [
			'attributes' => ['alias' => 'fail'],
			'code' => '',
			'script' => function() { throw new \Exception('boom'); }
		];

		$this -> tb -> insert('scripts', [
			'uniq_name' => 'fail',
			'type' => 'regular',
			'state' => 'enabled',
			'create_at' => date('Y-m-d H:i:s'),
		]);

		$this -> assertFalse(ControlScripts::run_regular_script('fail'));
	}

	public function test_run_regular_script_returns_true_on_success(): void {
		app() -> scripts_registry -> regular['ok'] = [
			'attributes' => ['alias' => 'ok'],
			'code' => '',
			'script' => function() { return true; }
		];

		$this -> tb -> insert('scripts', [
			'uniq_name' => 'ok',
			'type' => 'regular',
			'state' => 'enabled',
			'create_at' => date('Y-m-d H:i:s'),
		]);

		$this -> assertTrue(ControlScripts::run_regular_script('ok'));
	}
}
