<?php

namespace App\Modules\Settings\Rbac\Services;

use App\Models\User;
use App\Modules\Admin\ActivityLog\DTOs\ActivityLogWriteData;
use App\Modules\Admin\ActivityLog\Services\ActivityLogService;
use App\Modules\Settings\Rbac\Models\Role;

class RbacAuditService
{
    public function __construct(
        private readonly ActivityLogService $activityLog,
    ) {}

    public function role(Role $role, string $action): void
    {
        $this->log(
            (int) $role->tenant_id,
            $action,
            Role::class,
            (int) $role->id,
            __('activity_logs.actions.role_'.$action, ['name' => $role->name]),
        );
    }

    public function user(User $user, string $action): void
    {
        $this->log(
            (int) $user->tenant_id,
            $action,
            User::class,
            (int) $user->id,
            __('activity_logs.actions.user_'.$action, ['name' => $user->name]),
        );
    }

    private function log(
        int $tenantId,
        string $action,
        string $entityType,
        int $entityId,
        string $description,
    ): void {
        if ($tenantId < 1) {
            return;
        }
        $actor = auth()->user();
        $this->activityLog->log(new ActivityLogWriteData(
            tenantId: $tenantId,
            userId: $actor instanceof User ? (int) $actor->id : null,
            module: 'settings',
            action: $action,
            entityType: $entityType,
            entityId: $entityId,
            description: $description,
        ));
    }
}
