<?php

declare(strict_types=1);

namespace Plugin\tnt_stabila_shop\src\DomainObjects;

use DateException;
use DateTime;
use JsonException;
use Plugin\tnt_stabila_shop\src\Helper\ShopRuntime;

class StabilaDataDTO
{
    public function __construct(
        public int $id,
        public string $exceptionType,
        public string $sdkVersion,
        public object $extra,
        public string $filePath,
        public string $functionName,
        public string $template,
        public string $shopVersion,
        public string $message,
        public string $hash,
        public DateTime $createDate,
    ) {
    }

    /**
     * Create a StabilaDataDTO instance from an object containing table data.
     *
     * @param object|null $data
     */
    public static function initFromTableData(object|null $data): self|null
    {
        if ($data === null) {
            return null;
        }

        $createDateString = \is_string($data->createDate ?? null) ? $data->createDate : 'now';
        try {
            $createDate = new DateTime($createDateString, ShopRuntime::timezone());
        } catch (DateException) {
            $createDate = new DateTime();
        }

        try {
            $extra = \json_decode(\is_string($data->extra ?? null) ? $data->extra : '{}', true, 512, JSON_THROW_ON_ERROR);
        } catch (JsonException) {
            $extra = [];
        }

        return new self(
            id: \is_numeric($data->id ?? null) ? (int)$data->id : 0,
            exceptionType: \is_string($data->exceptionType ?? null) ? $data->exceptionType : '',
            sdkVersion: \is_string($data->sdkVersion ?? null) ? $data->sdkVersion : '',
            extra: \is_array($extra) ? (object)$extra : (object)[],
            filePath: \is_string($data->filePath ?? null) ? $data->filePath : '',
            functionName: \is_string($data->functionName ?? null) ? $data->functionName : '',
            template: \is_string($data->template ?? null) ? $data->template : '',
            shopVersion: \is_string($data->shopVersion ?? null) ? $data->shopVersion : '',
            message: \is_string($data->message ?? null) ? $data->message : '',
            hash: \is_string($data->hash ?? null) ? $data->hash : '',
            createDate: $createDate,
        );
    }
}
