<?php

namespace App\Actions\Transmittal;

use Closure;
use Exception;
use LogicException;
use App\Actions\BaseAction;
use App\Commands\Transmittal\StoreTransmittalCommand;
use App\DataObjects\CreateTransmittalDTO;
use Illuminate\Support\Arr;
use Spatie\LaravelData\Data;

class CreateTransmittal extends BaseAction
{

    public function __construct(
        private readonly StoreTransmittalCommand $storeTransmittalCommand
    ) {}

    public function __invoke(CreateTransmittalDTO | Data $payload, Closure $next)
    {
        try {
            $payload->transmittal = $this->storeTransmittalCommand->execute(Arr::except($payload->data, ['files']));

            return $next($payload);
        } catch (Exception $exception)
        {
            throw new LogicException('Error creating transmittal: ' . $exception->getMessage());
        }
    }
}
