<?php

use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\ObjectType;
use App\GraphQL\Types\JsonType;

$gql->queries['fields']['pageByRoute'] = [

    'type' => JsonType::instance(),

    'args' => [
        'route'  => Type::nonNull(Type::string()),
        'locale'  => Type::string(),
        'populate'   => ['type' => Type::int(), 'defaultValue' => 0],
    ],

    'resolve' => function ($root, $args) use($app) {

        if (!$app->helper('acl')->isAllowed('pages/api/read', $app->helper('auth')->getUser('role'))) {
            $app->response->status = 403;
            return null;
        }

        $options = [
            'locale' => $args['locale'] ?? 'default',
            'populate' => $args['populate'] ?? 0
        ];

        $page = $app->module('pages')->pageByRoute($args['route'], $options);

        if ($page && $page['_state'] != 1) {
            $page = null;
        }

        if ($page) {
            $app->trigger('pages.api.page', [&$page]);
        }

        return $page;
    }
];

$gql->queries['fields']['pageByID'] = [

    'type' => JsonType::instance(),

    'args' => [
        'id'  => Type::nonNull(Type::string()),
        'locale'  => Type::string(),
        'populate'   => ['type' => Type::int(), 'defaultValue' => 0],
    ],

    'resolve' => function ($root, $args) use($app) {

        if (!$app->helper('acl')->isAllowed('pages/api/read', $app->helper('auth')->getUser('role'))) {
            $app->response->status = 403;
            return null;
        }

        $options = [
            'locale' => $args['locale'] ?? 'default',
            'populate' => $args['populate'] ?? 0
        ];

        $page = $app->dataStorage->findOne('pages', ['_id' => $args['id'], '_state' => 1]);

        if ($page) {
            $page = $app->helper('pages')->processPage($page, $options);
        }

        return $page;
    }
];
