<?php

declare(strict_types=1);

namespace App\Support;

use Filament\Notifications\Notification;
use Filament\Support\Exceptions\Halt;
use Illuminate\Validation\ValidationException;

final class DberpFilamentInventoryConfirmActionFeedback
{
    public static function runWithFailureNotification(callable $callback): void
    {
        try {
            $callback();
        } catch (ValidationException $exception) {
            self::notifyValidationException($exception);

            throw new Halt;
        } catch (\Throwable) {
            Notification::make()
                ->title((string) __('dberp.notifications.inventory_confirm_failed_title'))
                ->body((string) __('dberp.errors.inventory_confirm_failed_generic'))
                ->danger()
                ->persistent()
                ->send();

            throw new Halt;
        }
    }

    private static function notifyValidationException(ValidationException $exception): void
    {
        $flattened = [];

        foreach ($exception->errors() as $group) {
            foreach ($group as $message) {
                $flattened[] = $message;
            }
        }

        $body = $flattened[0] ?? (string) __('dberp.errors.inventory_confirm_failed_generic');

        Notification::make()
            ->title((string) __('dberp.notifications.inventory_confirm_failed_title'))
            ->body((string) $body)
            ->danger()
            ->persistent()
            ->send();
    }
}
