<?php

namespace Planaday\Database\MySQL\QueryBuilding\SQLOperators;

use Planaday\Database\Abstraction\SQLQuery\QueryBuilding\SQLOperators\SQLComparison;
use Planaday\Database\Abstraction\SQLQuery\QueryBuilding\SQLOperators\SQLSubqueryComparisonModifier;
use Planaday\Database\Abstraction\SQLQuery\QueryBuilding\SQLUseInterfaces\SQLComparable;
use Planaday\Platform\PlatformAbstraction\DataHandler;

class MySQLComparison implements SQLComparison {
	protected string $operator;

	/**
	 * @param DataHandler $dataHandler
	 * @param SQLComparable $toBeTested
	 * @param null|string|int|float|SQLSubqueryComparisonModifier $value
	 * @param bool $isEqual
	 * @param bool|null $isGreater
	 */
	public function __construct(
		protected DataHandler $dataHandler,
		protected SQLComparable $toBeTested,
		protected null|string|int|float|SQLSubqueryComparisonModifier $value,
		bool $isEqual,
		?bool $isGreater = null
	) {
		$this->operator = '';
		if (isset($isGreater)){
			$this->operator .= ($isGreater ? '>' : '<');
		} else {
			if (!$isEqual) $this->operator .= '!=';
		}

		if ($isEqual) $this->operator .= '=';
	}

	function toConditionQuery(): string {
		if ($this->value === null) return $this->toBeTested->getCompareIdentifier() . ($this->operator == '!=' ? 'IS NOT NULL' : ' IS NULL');
		if (is_string($this->value)) $this->value = "'" . $this->dataHandler->escapeSql($this->value) . "'";
		if ( $this->value instanceof SQLSubqueryComparisonModifier) $this->value = $this->value->toQuery();

		return $this->toBeTested->getCompareIdentifier() .
		       ' '. $this->operator . ' ' . $this->value;
	}
}