<?php

declare(strict_types=1);

namespace apexl\Io\dto\Relationship\Decorators;

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

final readonly class DefaultPivotWeight implements PivotSqlFragment
{
    public function __construct(private Vault $db)
    {
    }

    public function render(RelationshipViaPivotInterface $relationship): string
    {
        $query = $this->db->newQuery()
            ->select($relationship->getPivotTable())
            ->fields(['1 + IFNULL(MAX(weight),0)'])
            ->whereRaw(
                sprintf(
                    '%s.%s = \'%s\'',
                    $relationship->getPivotTable(),
                    $relationship->getPivotLocal(),
                    $relationship->localEntity->{$relationship->localEntity->getPrimaryKey()},
                )
            );

        foreach ($relationship->getPivotFields() as $field => $value) {
            $query->whereRaw(
                sprintf('%s.%s = \'%s\'', $relationship->getPivotTable(), $field, $value),
            );
        }

        return sprintf('(SELECT * FROM (%s) weight)', $query->query->getStatement());
    }
}
