<?php

declare(strict_types=1);

namespace apexl\Io\dto\Relationship\Decorators;

use apexl\Io\interfaces\QueryDecorator;
use apexl\Io\interfaces\RelationshipInterface;
use apexl\Vault\enums\WhereCondition;
use apexl\Vault\enums\WhereType;
use apexl\Vault\interfaces\driver;

/**
 * Adds a WHERE clause keyed off a column on the relationship's aliased remote table.
 */
final readonly class WhereRemoteField implements QueryDecorator
{
    public function __construct(
        public string $field,
        public mixed $value,
        public WhereCondition $condition = WhereCondition::EQUALS,
        public WhereType $type = WhereType::AND,
    ) {
    }

    public function decorate(RelationshipInterface $relationship, driver $query): driver
    {
        return $query->where(
            sprintf('%s.%s', $relationship->getAliasedRemoteTable(), $this->field),
            $this->value,
            $this->condition,
            $this->type,
        );
    }
}
