using GraphQL;
using GraphQL.Types;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Performance.DtoModels;
using System.Threading.Tasks;

namespace Performance.Api
{
    [AllowAnonymous]
    [Route("api/graphql")]
    [ApiController]
    public class GraphQLController : ControllerBase
    {
        public ISchema performanceSchema { get; }
        public IDocumentExecuter documentExecuter { get; }
        public ILogger logger { get; set; }

        public GraphQLController(ISchema performanceSchema, IDocumentExecuter documentExecuter, ILogger<GraphQLController> logger)
        {
            this.performanceSchema = performanceSchema;
            this.documentExecuter = documentExecuter;
            this.logger = logger;
        }

        /// <summary>
        /// GraphQL请求地址
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResponse> Post(GraphQLRequest query)
        {
            var result = await documentExecuter.ExecuteAsync(options =>
            {
                options.Schema = performanceSchema;
                options.Query = query.Query;
            });

            if (result.Errors?.Count > 0)
            {
                return new ApiResponse(ResponseType.Error, result.Errors);
            }

            return new ApiResponse(ResponseType.OK, result.Data);
        }
    }
}
