<?php

namespace App\Actions\Ledgers;

use App\Actions\BaseAction;
use App\Commands\Ledgers\CreateLedgerCommand;
use App\DataObjects\CreateBalanceDTO;
use App\DataObjects\CreateLedgerDTO;
use Closure;
use Spatie\LaravelData\Data;

class CreateLedgerAction extends BaseAction
{
    public function __construct(
        private readonly CreateLedgerCommand $createLedgerCommand,
    ) {}

    public function __invoke(CreateLedgerDTO|Data $payload, Closure $next)
    {
        $ledger = $this->createLedgerCommand->execute($payload->data);

        $payload->balanceDTO = new CreateBalanceDTO(
            amount: $payload->amount,
            is_starting: false,
            ledger_id: $ledger->id,
            account_id: $ledger->account_id,
            branch_id: $ledger->branch_id,
            type: $payload->type ?? 'debit',
        );

        return $next($payload);
    }
}
