<?php

namespace Lucent\Command;

use Lucent\Command\Data\CommandLogItem;
use Lucent\Database\Database;

class CommandRepo
{
    public function findBySignature($signature): ?CommandLogItem
    {

        $row = Database::make()->table("command_logs")->where("signature", $signature)->first();
        if (empty($row)) {
            return null;
        }
        return CommandLogItem::fromDB($row);
    }


    public function upsertCommand(CommandLogItem $commandLogItem): void
    {
        $foundCommandLogItem = $this->findBySignature($commandLogItem->signature);
        if (empty($foundCommandLogItem)) {
            Database::make()->table("command_logs")->insert(toArray($commandLogItem));
            return;
        }

        Database::make()->table("command_logs")->where("signature", $commandLogItem->signature)->update(toArray($commandLogItem));
    }

    public function appendToLogs(string $signature, string $line): void
    {
        Database::make()->update(
            'update command_logs set logs = logs || ?  where signature = ?',
            [$line, $signature]
        );

    }
}