using System.Threading.Tasks;
using GraphQL;
using Microsoft.AspNetCore.Mvc;
using NewWebApi.GraphQLStruct;

namespace NewWebApi.Controllers
{
    public class GraphQLController : Controller
    {
        [Route("graphql")]
        [HttpPost]
        public async Task<IActionResult> GraphQL([FromBody] GraphQLQuery query)
        {
            var schema = new Schema.MySchema().Schema;

            var executer = await new DocumentExecuter().ExecuteAsync(option =>
             {
                 option.Schema = schema;
                 option.Query = query.Query;
                 option.OperationName = query.OperationName;
                 option.Inputs = query.Variables.ToInputs();
             });

            // OR
            //var executer = schema.Execute(option =>
            //  {
            //      option.Query = query.Query;
            //      option.OperationName = query.OperationName;
            //      option.Inputs = query.Variables.ToInputs();
            //  });

            if (executer.Errors?.Count > 0)
            {
                return BadRequest();
            }

            return Ok(executer);
        }
    }
}