<?php

namespace Opencart\Extension\Alsendo\DTO\Entity;

class LogEntity
{
    public int $id;
    public ?string $entityType;
    public ?int $entityId;
    public string $logType;
    public string|array $data;

    public static function fromArray(array $data): self
    {
        $dto = new self();
        $dto->id = (int)($data['id'] ?? 0);
        $dto->entityType = $data['entityType'] ?? null;
        $dto->entityId = isset($data['entityId']) ? (int)$data['entityId'] : null;
        $dto->logType = $data['logType'];
        $rawData = $data['data'] ?? '';
        $decoded = json_decode($rawData, true);
        $dto->data = (is_string($rawData) && json_last_error() === JSON_ERROR_NONE && is_array($decoded))
            ? $decoded
            : $rawData;

        return $dto;
    }

    public function getMessage(): string {
        if (is_string($this->data)) {
            return $this->data;
        } else {
            return json_encode($this->data);
        }
    }
}