<?php

declare(strict_types=1);

namespace Dalten\RuianToUir\Tests\Unit\Formatter;

use Dalten\RuianToUir\ItemType;
use Dalten\RuianToUir\Converter\Field\Point;
use Dalten\RuianToUir\Converter\Result\AddRecord;
use Dalten\RuianToUir\Converter\Result\RemoveRecord;
use Dalten\RuianToUir\Formatter\Sql;
use PHPUnit\Framework\TestCase;

use PHPUnit\Framework\Attributes\CoversClass;

#[CoversClass(Sql::class)]
final class SqlTest extends TestCase
{
    private function type(): ItemType
    {
        return ItemType::Address;
    }

    public function testOutputsSqlForAddRecordWithGeometryAndEscaping(): void
    {
        $type = $this->type();
        $formatter = new Sql();

        $idCol = $type->primaryKey();
        $data = [
            $idCol => 123,
            'psc' => '110 00',
            'note' => "O'Reilly",
            'geom' => new Point('50.087451 14.420671'),
        ];

        $result = new AddRecord('Address', 123, $data);

        $sql = $formatter->format($result);

        $table = $type->tableName();
        $expected = \sprintf(
            "REPLACE INTO `%s` (`%s`, `psc`, `note`, `geom`) VALUES ('123', '110 00', 'O\\'Reilly', ST_GeomFromText('Point(50.087451 14.420671)'));",
            $table,
            $idCol
        );
        $this->assertSame($expected, $sql);
    }

    public function testOutputsSqlForRemoveRecordWithIdentifier(): void
    {
        $type = $this->type();
        $formatter = new Sql();

        $result = new RemoveRecord('Address', 98765);

        $sql = $formatter->format($result);

        $table = $type->tableName();
        $idCol = $type->primaryKey();
        $this->assertSame(\sprintf('UPDATE `%s` SET `stav` = 0 WHERE `%s` = 98765 LIMIT 1;', $table, $idCol), $sql);
    }

    public function testThrowsWhenConverterNameIsUnknown(): void
    {
        $formatter = new Sql();

        $result = new RemoveRecord('Unknown', 1);

        $this->expectException(\InvalidArgumentException::class);
        $formatter->format($result);
    }
}
