<?php

namespace App\Modules\Exports\Listeners;

use App\Modules\Admin\ActivityLog\DTOs\ActivityLogWriteData;
use App\Modules\Admin\ActivityLog\Services\ActivityLogService;
use App\Modules\Exports\Events\ExportCompleted;
use App\Modules\Exports\Events\ExportFailed as ExportFailedEvent;
use App\Modules\Exports\Events\ExportRequested;
use App\Modules\Exports\Models\Export;

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

    public function handleRequested(ExportRequested $event): void
    {
        $this->log($event->export, 'export_requested', __('exports.activity.requested', [
            'id' => $event->export->id,
            'type' => $event->export->type,
        ]), (int) $event->export->user_id);
    }

    public function handleCompleted(ExportCompleted $event): void
    {
        $this->log($event->export, 'export_completed', __('exports.activity.completed', [
            'id' => $event->export->id,
        ]), (int) $event->export->user_id);
    }

    public function handleFailed(ExportFailedEvent $event): void
    {
        $this->log($event->export, 'export_failed', __('exports.activity.failed', [
            'id' => $event->export->id,
        ]), (int) $event->export->user_id);
    }

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