<?php

namespace App\Modules\Admin\ActivityLog\Listeners;

use App\Models\User;
use App\Modules\Admin\ActivityLog\DTOs\ActivityLogWriteData;
use App\Modules\Admin\ActivityLog\Services\ActivityLogService;
use App\Modules\HR\Employees\Events\EmployeeCreated;
use App\Modules\HR\Employees\Events\EmployeeDeactivated;
use App\Modules\HR\Employees\Events\EmployeeUpdated;
use App\Modules\HR\Employees\Models\Employee;

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

    public function handleCreated(EmployeeCreated $event): void
    {
        $this->log($event->employee, 'created', __('activity_logs.actions.employee_created', [
            'name' => $event->employee->full_name,
        ]));
    }

    public function handleUpdated(EmployeeUpdated $event): void
    {
        $this->log($event->employee, 'updated', __('activity_logs.actions.employee_updated', [
            'name' => $event->employee->full_name,
        ]));
    }

    public function handleDeactivated(EmployeeDeactivated $event): void
    {
        $this->log($event->employee, 'deactivated', __('activity_logs.actions.employee_deactivated', [
            'name' => $event->employee->full_name,
        ]));
    }

    private function log(Employee $employee, string $action, string $description): void
    {
        $tenantId = (int) $employee->tenant_id;
        if ($tenantId === 0) {
            return;
        }

        $user = auth()->user();
        $userId = $user instanceof User ? $user->id : null;

        $this->activityLog->log(new ActivityLogWriteData(
            tenantId: $tenantId,
            userId: $userId,
            module: 'hr',
            action: $action,
            entityType: Employee::class,
            entityId: $employee->id,
            description: $description,
        ));
    }
}
