<?php

namespace App\Framework\Logging;

use App\Framework\CommandBus\CommandHandler;
use App\Framework\Database\DatabaseManager;

final readonly class ProcessLogCommandHandler
{
    public function __construct(
        private DatabaseManager $db,
    ){}

    #[CommandHandler]
    public function __invoke(ProcessLogCommand $commandData): void
    {
        $data = $commandData->logData;
        $contextJson = json_encode($data->getContext());
        $contextHash = hash('sha256', $contextJson);

        // context_hash zur Eindeutigkeit in den Primärschlüssel aufgenommen
        $this->db->getConnection()->execute("CREATE TABLE IF NOT EXISTS logs (timestamp TIMESTAMP, level VARCHAR(10), message VARCHAR(255), context JSON, context_hash VARCHAR(64), PRIMARY KEY (timestamp, level, message, context_hash))");

        $this->db->getConnection()->execute(
            "INSERT INTO logs (timestamp, level, message, context, context_hash) VALUES (?, ?, ?, ?, ?)",
            [
                $data->getFormattedTimestamp(),
                $data->getLevel()->getName(),
                $data->getMessage(),
                $contextJson,
                $contextHash,
            ]
        );

    }
}
