<?php

namespace App\Modules\HR\Leave\Listeners;

use App\Modules\Admin\ActivityLog\DTOs\ActivityLogWriteData;
use App\Modules\Admin\ActivityLog\Services\ActivityLogService;
use App\Modules\HR\Leave\Events\LeaveRequestCancelled;
use App\Modules\HR\Leave\Events\LeaveRequestHrApproved;
use App\Modules\HR\Leave\Events\LeaveRequestManagerApproved;
use App\Modules\HR\Leave\Events\LeaveRequestRejected;
use App\Modules\HR\Leave\Events\LeaveRequestSubmitted;
use App\Modules\HR\Leave\Models\LeaveRequest;

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

    public function handleSubmitted(LeaveRequestSubmitted $event): void
    {
        $this->log($event->leaveRequest, 'leave_submitted', __('leave.activity.submitted', [
            'id' => $event->leaveRequest->id,
        ]), $event->actorUserId);
    }

    public function handleManagerApproved(LeaveRequestManagerApproved $event): void
    {
        $this->log($event->leaveRequest, 'leave_manager_approved', __('leave.activity.manager_approved', [
            'id' => $event->leaveRequest->id,
        ]), $event->approverUserId);
    }

    public function handleHrApproved(LeaveRequestHrApproved $event): void
    {
        $this->log($event->leaveRequest, 'leave_hr_approved', __('leave.activity.hr_approved', [
            'id' => $event->leaveRequest->id,
        ]), $event->approverUserId);
    }

    public function handleRejected(LeaveRequestRejected $event): void
    {
        $this->log($event->leaveRequest, 'leave_rejected', __('leave.activity.rejected', [
            'id' => $event->leaveRequest->id,
        ]), $event->approverUserId);
    }

    public function handleCancelled(LeaveRequestCancelled $event): void
    {
        $this->log($event->leaveRequest, 'leave_cancelled', __('leave.activity.cancelled', [
            'id' => $event->leaveRequest->id,
        ]), $event->actorUserId);
    }

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