<?php

declare(strict_types=1);

namespace Hexspoor\MonitorClient;

use Hexspoor\MonitorClient\Contracts\LoggerContract;
use Hexspoor\MonitorClient\Models\MonitorLog;

final class Logger implements LoggerContract
{
    private ?int $clientId = null;

    private ?string $clientName = null;

    private ?int $connectorId = null;

    private ?string $connectorName = null;

    private ?string $entityId = null;

    private ?int $entityTypeId = null;

    private ?int $systemId = null;

    public function setClient(int $clientId, string $clientName = null)
    {
        $this->clientId = $clientId;
        $this->clientName = $clientName;
    }

    public function setConnector(int $connectorId, string $connectorName = null)
    {
        $this->connectorId = $connectorId;
        $this->connectorName = $connectorName;
    }

    public function setEntity(?int $entityTypeId, $entityId = null)
    {
        $this->entityTypeId = $entityTypeId;
        if (null !== $entityId) {
            $this->entityId = (string) $entityId;
        }
    }

    public function setSystemId(int $systemId)
    {
        $this->systemId = $systemId;
    }

    public function log(
        string $message,
        int $logTypeId = LogType::LOG,
        ?int $statusCode = null,
        ?int $monitorRuleId = null
    ): int {
        $log = MonitorLog::query()->create([
            'log_type_id'     => $logTypeId,
            'monitor_rule_id' => $monitorRuleId,
            'system_id'       => $this->systemId,
            'client_id'       => $this->clientId,
            'client_name'     => $this->clientName,
            'connector_id'    => $this->connectorId,
            'connector_name'  => $this->connectorName,
            'entity_type_id'  => $this->entityTypeId,
            'entity_id'       => $this->entityId,
            'status_code'     => $statusCode,
            'message'         => $message,
        ]);

        return $log->getKey();
    }
}
