<?php

declare(strict_types=1);

namespace apexl\Io\dto\Relationship\Decorators;

use apexl\Io\interfaces\PivotSqlFragment;
use apexl\Io\interfaces\RelationshipViaPivotInterface;

/**
 * Renders a raw pivot-join fragment, substituting these placeholders in the template:
 *   #LOCAL_TABLE#  — relationship's local table
 *   #LOCAL_KEY#    — relationship's local key
 *   #PIVOT_ALIAS#  — pivot table alias
 *   #PIVOT_LOCAL#  — pivot local-side column
 */
final readonly class PivotJoinTemplate implements PivotSqlFragment
{
    public function __construct(public string $template)
    {
    }

    public function render(RelationshipViaPivotInterface $relationship): string
    {
        return str_replace(
            ['#LOCAL_TABLE#', '#LOCAL_KEY#', '#PIVOT_ALIAS#', '#PIVOT_LOCAL#'],
            [
                $relationship->getLocalTable(),
                $relationship->getLocalKey(),
                $relationship->getPivotTableAlias(),
                $relationship->getPivotLocal(),
            ],
            $this->template,
        );
    }
}
