<?php

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

class CronControllerTest 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,
			create_at TEXT,
			update_at TEXT
		)");
		ControlScripts::flush_statics();
	}

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

	public function test_regular_scripts_continue_after_failure(): void {
		$executed = [];

		// Inject test regular scripts directly into ControlScripts static storage
		$ref = new \ReflectionClass(ControlScripts::class);
		$prop = $ref -> getProperty('regular_scripts');
		$prop -> setAccessible(true);

		$scripts = [
			'fail_script' => [
				'attributes' => ['alias' => 'fail_script', 'name' => 'Fail'],
				'code' => '',
				'script' => function() use (&$executed) {
					$executed[] = 'fail';
					throw new \Exception('Intentional failure');
				}
			],
			'ok_script' => [
				'attributes' => ['alias' => 'ok_script', 'name' => 'OK'],
				'code' => '',
				'script' => function() use (&$executed) {
					$executed[] = 'ok';
				}
			]
		];
		$prop -> setValue(null, $scripts);

		// Enable both scripts in DB
		$this -> tb -> insert('scripts', [
			'uniq_name' => 'fail_script',
			'type' => 'regular',
			'state' => 'enabled',
			'create_at' => date('Y-m-d H:i:s'),
		]);
		$this -> tb -> insert('scripts', [
			'uniq_name' => 'ok_script',
			'type' => 'regular',
			'state' => 'enabled',
			'create_at' => date('Y-m-d H:i:s'),
		]);

		$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
		$controller = new CronController();
		$controller -> run_regular_cron_scripts();

		$this -> assertSame(['fail', 'ok'], $executed);
	}
}
