<?php

namespace App\Modules\Exports\Listeners;

use App\Models\User;
use App\Modules\Exports\Events\ExportCompleted;
use App\Modules\Exports\Events\ExportFailed;
use App\Modules\Exports\Models\Export;
use App\Modules\Exports\Notifications\ExportFinishedNotification;

class ExportNotificationListener
{
    public function handleCompleted(ExportCompleted $event): void
    {
        $this->notify($event->export->user_id, $event->export, true);
    }

    public function handleFailed(ExportFailed $event): void
    {
        $this->notify($event->export->user_id, $event->export, false);
    }

    private function notify(int $userId, Export $export, bool $success): void
    {
        $user = User::query()->whereKey($userId)->first();
        if ($user === null) {
            return;
        }
        if ($user->tenant_id === null || (int) $user->tenant_id !== (int) $export->tenant_id) {
            return;
        }
        $user->notify(new ExportFinishedNotification($export, $success));
    }
}
