<?php

namespace App\Listeners\Backup;

use App\Services\NotificationService;
use Spatie\Backup\Events\BackupHasFailed;
use Spatie\Backup\Events\BackupWasSuccessful;
use Spatie\Backup\Events\CleanupHasFailed;

class ForwardBackupNotification
{
    public function __construct(private NotificationService $notifications) {}

    public function handleSuccess(BackupWasSuccessful $event): void
    {
        if (! setting('backup_notify', true)) {
            return;
        }

        $this->notifications->notifyAdmins(
            'backup_success',
            __('admin/backups.notify_success_subject'),
            __('admin/backups.notify_success_body'),
        );
    }

    public function handleFailed(BackupHasFailed $event): void
    {
        // Başarısızlık her zaman bildirilir (kritik).
        $this->notifications->notifyAdmins(
            'backup_failed',
            __('admin/backups.notify_failed_subject'),
            __('admin/backups.notify_failed_body', ['error' => $event->exception?->getMessage() ?? '-']),
        );
    }

    public function handleCleanupFailed(CleanupHasFailed $event): void
    {
        $this->notifications->notifyAdmins(
            'backup_cleanup_failed',
            __('admin/backups.notify_cleanup_failed_subject'),
            __('admin/backups.notify_cleanup_failed_body'),
        );
    }

    public function subscribe($events): array
    {
        return [
            BackupWasSuccessful::class => 'handleSuccess',
            BackupHasFailed::class     => 'handleFailed',
            CleanupHasFailed::class    => 'handleCleanupFailed',
        ];
    }
}
