<?php

namespace Modules\AiAgent\Filament\Concerns;

use Filament\Notifications\Notification;
use Modules\Shared\Bnfexpress\Exceptions\BnfexpressApiException;

/**
 * Shared try/call/notify wrapper for bnfexpress admin API calls triggered
 * from a Filament action — every mutating action across the AI Agent pages
 * (create/update/delete/publish/activate) follows this same shape.
 */
trait HandlesBnfexpressErrors
{
    /**
     * @param  callable(): void  $callback
     */
    protected function callBnfexpress(callable $callback, string $successTitle, string $failureTitle): void
    {
        try {
            $callback();

            Notification::make()->title($successTitle)->success()->send();
        } catch (BnfexpressApiException $exception) {
            Notification::make()->title($failureTitle)->body($exception->getMessage())->danger()->send();
        }
    }

    /**
     * Same shape as callBnfexpress(), but for calls whose success notification
     * needs the response (e.g. a "{created} created, {skipped} skipped" body) —
     * $onSuccess builds/sends its own Notification from $callback()'s return value.
     *
     * @param  callable(): mixed  $callback
     * @param  callable(mixed): void  $onSuccess
     */
    protected function callBnfexpressForResult(callable $callback, callable $onSuccess, string $failureTitle): void
    {
        try {
            $onSuccess($callback());
        } catch (BnfexpressApiException $exception) {
            Notification::make()->title($failureTitle)->body($exception->getMessage())->danger()->send();
        }
    }
}
