<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Controller;

use idoit\Module\SyneticsFlows\Auth;
use idoit\Module\SyneticsFlows\Controller\Response\CiObjectArrayResponse;
use idoit\Module\SyneticsFlows\Controller\Response\NotFoundResponse;
use idoit\Module\SyneticsFlows\Filter\CiObjectFilter;
use idoit\Module\SyneticsFlows\Model\CiObjectDao;
use idoit\Module\SyneticsFlows\Serialization\Serializer;
use isys_auth;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class CiObjectController extends BaseController
{
    /**
     * @var CiObjectDao|null
     */
    private ?CiObjectDao $ciObjectDao = null;

    /**
     * @return CiObjectDao
     * @throws \Exception
     */
    public function getDao(): CiObjectDao
    {
        if (!$this->ciObjectDao) {
            $this->ciObjectDao = \isys_application::instance()->container->get('idoit.flows.object.dao');
        }
        return $this->ciObjectDao;
    }

    /**
     * @param Request $request
     *
     * @return Response
     * @throws \Exception
     */
    public function find(Request $request): Response
    {
        if (!Auth::instance()->manageFlows(isys_auth::VIEW)) {
            return JSONResponseFactory::accessDenied();
        }
        $params = $this->extractData($request);
        $search = Serializer::fromJson(SearchParams::class, $params);
        $filter = Serializer::fromJson(CiObjectFilter::class, $params['filter'] ?? []);
        $groupBy = $params['groupBy'] ?? null;
        $results = $this->getDao()->getData($filter, $search);
        $count = $this->getDao()->getCount($filter);
        $groups = $groupsAll = ['count' => 0, 'results' => []];

        if (is_string($groupBy)) {
            $groups = $this->getDao()->getGroups($groupBy, $filter);
            $groupsAll = $this->getDao()->getGroupsAll($groupBy, $filter);
        }

        return new CiObjectArrayResponse(
            $results,
            $count,
            $groups,
            $groupsAll
        );
    }

    /**
     * @param string $id
     *
     * @return Response
     * @throws \Exception
     */
    public function get(string $id): Response
    {
        if (!Auth::instance()->manageFlows(isys_auth::VIEW)) {
            return JSONResponseFactory::accessDenied();
        }

        $result = $this->getDao()->get($id);
        if ($result === null) {
            return new NotFoundResponse('Object');
        }
        return new JsonResponse($result);
    }
}
