<?php

namespace App\Services;

use App\Models\MlmLog;
use Illuminate\Support\Facades\Schema;

class MlmLogService
{
    private ?bool $isEnabled = null;

    /**
     * @param array<string, mixed> $data
     */
    public function log(string $eventType, ?int $userId = null, ?string $referenceType = null, ?int $referenceId = null, array $data = []): void
    {
        if (! $this->enabled()) {
            return;
        }

        try {
            MlmLog::query()->create([
                'event_type' => $eventType,
                'user_id' => $userId,
                'reference_type' => $referenceType,
                'reference_id' => $referenceId,
                'data' => $data,
                'logged_at' => now(),
            ]);
        } catch (\Throwable) {
            // Intentionally swallow log failures to avoid impacting financial transactions.
        }
    }

    private function enabled(): bool
    {
        if ($this->isEnabled !== null) {
            return $this->isEnabled;
        }

        $this->isEnabled = Schema::hasTable('mlm_logs');

        return $this->isEnabled;
    }
}
