<?php

namespace App\Services\Intune;

use App\Models\AuditLog;
use App\Models\Tenant;
use App\Support\Audit\AuditContextSanitizer;
use Carbon\CarbonImmutable;
use InvalidArgumentException;

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']);

        $metadata = is_array($metadata) ? $metadata : [];

        $sanitizedMetadata = AuditContextSanitizer::sanitize($metadata + $context);
        $workspaceId = is_numeric($tenant->workspace_id) ? (int) $tenant->workspace_id : null;

        if ($workspaceId === null) {
            throw new InvalidArgumentException('Tenant-scoped audit events require tenant workspace_id.');
        }

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