<?php

namespace App\Actions\Transmittal;

use Closure;
use Exception;
use LogicException;
use App\Actions\BaseAction;
use App\Commands\Transmittal\StoreCommentCommand;
use App\Commands\Transmittal\StoreFileCommand;
use App\Commands\Transmittal\StoreRemarkCommand;
use App\DataObjects\CreateCommentDTO;
use App\DataObjects\CreateFileDTO;
use App\DataObjects\CreateRemarkDTO;
use App\DataObjects\CreateTransmittalDTO;
use Illuminate\Support\Arr;
use Spatie\LaravelData\Data;

class CreateTransmittalFiles extends BaseAction
{

    public function __construct(
        private readonly StoreFileCommand    $storeFileCommand,
        private readonly StoreCommentCommand $storeCommentCommand,
        private readonly StoreRemarkCommand  $storeRemarkCommand
    ) {}

    public function __invoke(CreateTransmittalDTO | Data $payload, Closure $next)
    {
        try {
            $files = Arr::only($payload->data, 'files');
            $filesCreated = [];
            foreach ($files as $file) {

                //save each file
                $filePayload = new CreateFileDTO(transmittal_id: $payload->transmittal->id, description: Arr::first($file)['description']);
                $fileCreated = $this->storeFileCommand->execute($filePayload->except('file')->toArray());


                $comments = Arr::first($file)['comments'];
                $remarks = Arr::first($file)['remarks'];

                //save each comments of each file
                foreach ($comments as $key => $comment) {
                    $commentPayload = new CreateCommentDTO(file_id: $fileCreated->id, comment: $comment['comment']);
                    $this->storeCommentCommand->execute($commentPayload->except('commentModel')->toArray());
                }

                //save each remarks of each file
                foreach ($remarks as $key => $remark) {
                    $remarkPayload = new CreateRemarkDTO(file_id: $fileCreated->id, remark: $remark['remark']);
                    $this->storeRemarkCommand->execute($remarkPayload->except('remarkModel')->toArray());
                }

                $filesCreated[] = $fileCreated;
            }

            $payload->files = $filesCreated;

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