<?php

namespace App\Actions\Account;

use App\Actions\BaseAction;
use App\Commands\Account\CreateBalanceCommand;
use App\DataObjects\CreateAccountDTO;
use Closure;
use Exception;
use LogicException;
use Spatie\LaravelData\Data;

class StoreAccountBalance extends BaseAction
{
    public function __construct(private readonly CreateBalanceCommand $createBalanceCommand) {}

    public function __invoke(CreateAccountDTO|Data $payload, Closure $next)
    {
        try {

            $payload->data['account_id'] = $payload->account->id;
            $payload->balance = $this->createBalanceCommand->execute($payload->data);

            return $next($payload->account);

        } catch (Exception $exception) {
            throw new LogicException('Error Storing Account Balance: '.$exception->getMessage());
        }
    }
}
