<?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\WhereType;
use apexl\Vault\interfaces\driver;

/**
 * Adds a raw WHERE clause, substituting these placeholders in the template:
 *   #REMOTE_TABLE# — relationship's aliased remote table
 *   #LOCAL_TABLE#  — relationship's local table
 */
final readonly class WhereRawTemplate implements QueryDecorator
{
    /**
     * @param array<int|string, mixed> $params
     */
    public function __construct(
        public string $template,
        public array $params = [],
        public WhereType $type = WhereType::AND,
    ) {
    }

    public function decorate(RelationshipInterface $relationship, driver $query): driver
    {
        return $query->whereRaw(
            str_replace(
                ['#REMOTE_TABLE#', '#LOCAL_TABLE#'],
                [$relationship->getAliasedRemoteTable(), $relationship->getLocalTable()],
                $this->template,
            ),
            $this->params,
            $this->type,
        );
    }
}
