<?php

namespace App\Modules\HR\PermissionRequests\Listeners;

use App\Modules\Admin\ActivityLog\DTOs\ActivityLogWriteData;
use App\Modules\Admin\ActivityLog\Services\ActivityLogService;
use App\Modules\HR\PermissionRequests\Events\PermissionRequestApproved;
use App\Modules\HR\PermissionRequests\Events\PermissionRequestRejected;
use App\Modules\HR\PermissionRequests\Events\PermissionRequestSubmitted;
use App\Modules\HR\PermissionRequests\Models\PermissionRequest;

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

    public function handleSubmitted(PermissionRequestSubmitted $event): void
    {
        $this->log($event->permissionRequest, 'permission_request_submitted', __('permission_requests.activity.submitted', [
            'id' => $event->permissionRequest->id,
        ]), $event->actorUserId);
    }

    public function handleApproved(PermissionRequestApproved $event): void
    {
        $this->log($event->permissionRequest, 'permission_request_approved', __('permission_requests.activity.approved', [
            'id' => $event->permissionRequest->id,
        ]), $event->reviewerUserId);
    }

    public function handleRejected(PermissionRequestRejected $event): void
    {
        $this->log($event->permissionRequest, 'permission_request_rejected', __('permission_requests.activity.rejected', [
            'id' => $event->permissionRequest->id,
        ]), $event->reviewerUserId);
    }

    private function log(PermissionRequest $request, string $action, string $description, int $userId): void
    {
        $tenantId = (int) $request->tenant_id;
        if ($tenantId < 1) {
            return;
        }
        $this->activityLog->log(new ActivityLogWriteData(
            tenantId: $tenantId,
            userId: $userId,
            module: 'hr',
            action: $action,
            entityType: PermissionRequest::class,
            entityId: $request->id,
            description: $description,
        ));
    }
}
