<?php

declare(strict_types=1);

namespace Apexl\Io\Dtos\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\QueryBuilderInterface;

/**
 * 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, QueryBuilderInterface $query): QueryBuilderInterface
    {
        return $query->where(
            sprintf('%s.%s', $relationship->getAliasedRemoteTable(), $this->field),
            $this->value,
            $this->condition,
            $this->type,
        );
    }
}
