<?php

namespace Velis\Mvc\Controller\Listeners;

use Velis\Dto\BaseDto;
use Velis\Dto\Common\Result\ListResult;
use Velis\Dto\Common\Result\PaginatedListResult;
use Velis\Dto\Common\Result\Result;
use Velis\Mvc\Controller\Listeners\Concrete\AbstractListener;

class WrapDataListener extends AbstractListener
{
    public function handle(): void
    {
        $data = $this->dispatcher->getReturnedValue();

        if (
            $data instanceof Result
            || $data instanceof PaginatedListResult
            || $data instanceof ListResult
        ) {
            $this->response->setJsonContent($data);
            return;
        }

        if ($data instanceof BaseDto) {
            $data = $data->toArray();
        }

        if ($data || is_array($data)) {
            $this->response->setJsonContent([
                'data' => $data
            ]);
        }
    }
}
