<?php

namespace App\Services\Intune;

use App\Models\AuditLog;
use App\Models\Tenant;
use Carbon\CarbonImmutable;

class AuditLogger
{
    public function log(
        Tenant $tenant,
        string $action,
        array $context = [],
        ?int $actorId = null,
        ?string $actorEmail = null,
        ?string $actorName = null,
        string $status = 'success',
        ?string $resourceType = null,
        ?string $resourceId = null,
    ): AuditLog {
        $metadata = $context['metadata'] ?? [];
        unset($context['metadata']);

        return AuditLog::create([
            'tenant_id' => $tenant->id,
            'actor_id' => $actorId,
            'actor_email' => $actorEmail,
            'actor_name' => $actorName,
            'action' => $action,
            'resource_type' => $resourceType,
            'resource_id' => $resourceId,
            'status' => $status,
            'metadata' => $metadata + $context,
            'recorded_at' => CarbonImmutable::now(),
        ]);
    }
}
