<?php

namespace App\Modules\HR\Overtime\Listeners;

use App\Modules\Admin\ActivityLog\DTOs\ActivityLogWriteData;
use App\Modules\Admin\ActivityLog\Services\ActivityLogService;
use App\Modules\HR\Overtime\Events\OvertimeRequestApproved;
use App\Modules\HR\Overtime\Events\OvertimeRequestCancelled;
use App\Modules\HR\Overtime\Events\OvertimeRequestRejected;
use App\Modules\HR\Overtime\Events\OvertimeRequestSubmitted;
use App\Modules\HR\Overtime\Models\OvertimeRequest;

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

    public function handleSubmitted(OvertimeRequestSubmitted $event): void
    {
        $this->log(
            $event->overtimeRequest,
            'overtime_submitted',
            __('activity_logs.actions.overtime_submitted', ['id' => $event->overtimeRequest->id]),
            $event->actorUserId,
        );
    }

    public function handleApproved(OvertimeRequestApproved $event): void
    {
        $this->log(
            $event->overtimeRequest,
            'overtime_approved',
            __('activity_logs.actions.overtime_approved', ['id' => $event->overtimeRequest->id]),
            $event->reviewerUserId,
        );
    }

    public function handleRejected(OvertimeRequestRejected $event): void
    {
        $this->log(
            $event->overtimeRequest,
            'overtime_rejected',
            __('activity_logs.actions.overtime_rejected', ['id' => $event->overtimeRequest->id]),
            $event->reviewerUserId,
        );
    }

    public function handleCancelled(OvertimeRequestCancelled $event): void
    {
        $this->log(
            $event->overtimeRequest,
            'overtime_cancelled',
            __('activity_logs.actions.overtime_cancelled', ['id' => $event->overtimeRequest->id]),
            $event->actorUserId,
        );
    }

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