<?php

namespace App\Modules\HR\Recruitment\Listeners;

use App\Modules\Admin\ActivityLog\DTOs\ActivityLogWriteData;
use App\Modules\Admin\ActivityLog\Services\ActivityLogService;
use App\Modules\HR\Recruitment\Events\RecruitmentOfferLetterCreated;
use App\Modules\HR\Recruitment\Events\RecruitmentOfferLetterDeleted;
use App\Modules\HR\Recruitment\Events\RecruitmentOfferLetterStatusChanged;
use App\Modules\HR\Recruitment\Events\RecruitmentOfferLetterUpdated;
use Illuminate\Database\Eloquent\Model;

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

    public function handleCreated(RecruitmentOfferLetterCreated $e): void
    {
        $this->log($e->offerLetter, 'recruitment_offer_created', __('recruitment.activity.offer_created', [
            'ref' => $e->offerLetter->reference_code,
        ]));
    }

    public function handleUpdated(RecruitmentOfferLetterUpdated $e): void
    {
        $this->log($e->offerLetter, 'recruitment_offer_updated', __('recruitment.activity.offer_updated', [
            'ref' => $e->offerLetter->reference_code,
        ]));
    }

    public function handleDeleted(RecruitmentOfferLetterDeleted $e): void
    {
        $this->log($e->offerLetter, 'recruitment_offer_deleted', __('recruitment.activity.offer_deleted', [
            'ref' => $e->offerLetter->reference_code,
        ]));
    }

    public function handleStatusChanged(RecruitmentOfferLetterStatusChanged $e): void
    {
        $this->log($e->offerLetter, 'recruitment_offer_'.$e->action, __('recruitment.activity.offer_status_changed', [
            'ref' => $e->offerLetter->reference_code,
            'action' => __('recruitment.offer_letters.actions.'.$e->action),
            'from' => $e->fromStatus ? __('recruitment.offer_letters.status.'.$e->fromStatus) : '—',
            'to' => __('recruitment.offer_letters.status.'.$e->toStatus),
        ]));
    }

    private function log(Model $entity, string $action, string $description): void
    {
        $tenantId = (int) ($entity->getAttribute('tenant_id') ?? 0);
        $uid = (int) (auth()->id() ?? 0);
        if ($tenantId < 1 || $uid < 1) {
            return;
        }
        $this->activityLog->log(new ActivityLogWriteData(
            tenantId: $tenantId,
            userId: $uid,
            module: 'hr',
            action: $action,
            entityType: $entity::class,
            entityId: (int) $entity->getKey(),
            description: $description,
        ));
    }
}
