<?php
declare(strict_types=1);

namespace apexl\Vault\Tests;

use apexl\Vault\operators\drivers\mysql;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use stdClass;

/**
 * Builder-level coverage for the INSERT ... ON DUPLICATE KEY UPDATE SQL the
 * 3.1.x driver attaches to every insert. No database needed — the mysql
 * driver connects lazily, so we can construct it, build a query, and inspect
 * the generated SQL via the public $query object.
 */
final class MysqlInsertBuilderTest extends TestCase
{
    private function driver(): mysql
    {
        $cfg = new stdClass();
        $cfg->driver = 'mysql';
        $cfg->dbhost = 'localhost';
        $cfg->dbname = 'unused';
        $cfg->dbuser = 'unused';
        $cfg->dbpass = 'unused';

        return new mysql($cfg);
    }

    /**
     * Reserved-word columns (`key`, `condition`, ...) must be backticked
     * inside VALUES() — the raw form is a MySQL 1064 syntax error, which
     * broke every insert on tables with a `key` column (e.g. settings).
     */
    #[Test]
    public function insert_backticks_reserved_word_columns_in_values_refs(): void
    {
        $drv = $this->driver();
        $drv->insert('settings')->fields(['key' => 'a.b', 'value' => '1']);

        $sql = $drv->query->getStatement();

        self::assertStringContainsString('ON DUPLICATE KEY UPDATE', $sql);
        self::assertStringContainsString('VALUES(`key`)', $sql);
        self::assertStringContainsString('VALUES(`value`)', $sql);
        self::assertStringNotContainsString('VALUES(key)', $sql);
    }
}
