<?php

namespace App\Services\Stats;

use App\Models\Stats\StatEvent;
use App\Models\Stats\StatSnapshot;
use Illuminate\Support\Facades\Log;

class StatEventService
{
    /**
     * 통계 이벤트 기록
     */
    public function recordEvent(
        int $tenantId,
        string $domain,
        string $eventType,
        string $entityType,
        int $entityId,
        ?array $payload = null
    ): void {
        try {
            StatEvent::create([
                'tenant_id' => $tenantId,
                'domain' => $domain,
                'event_type' => $eventType,
                'entity_type' => $entityType,
                'entity_id' => $entityId,
                'payload' => $payload,
                'occurred_at' => now(),
            ]);
        } catch (\Throwable $e) {
            Log::warning('stat_event 기록 실패', [
                'tenant_id' => $tenantId,
                'domain' => $domain,
                'event_type' => $eventType,
                'error' => $e->getMessage(),
            ]);
        }
    }

    /**
     * 스냅샷 저장
     */
    public function saveSnapshot(
        int $tenantId,
        string $domain,
        string $snapshotDate,
        array $data,
        string $snapshotType = 'daily'
    ): void {
        try {
            StatSnapshot::updateOrCreate(
                [
                    'tenant_id' => $tenantId,
                    'snapshot_date' => $snapshotDate,
                    'domain' => $domain,
                    'snapshot_type' => $snapshotType,
                ],
                [
                    'data' => $data,
                    'created_at' => now(),
                ]
            );
        } catch (\Throwable $e) {
            Log::warning('stat_snapshot 저장 실패', [
                'tenant_id' => $tenantId,
                'domain' => $domain,
                'snapshot_date' => $snapshotDate,
                'error' => $e->getMessage(),
            ]);
        }
    }
}
