package com.purui.prims.headless.server.rest.api;

import com.purui.prims.auth.api.authentication.pojo.User;
import com.purui.prims.auth.api.authentication.utils.UserHolder;
import com.purui.prims.common.pojo.enums.QueryType;
import com.purui.prims.headless.api.pojo.request.QueryDataSetReq;
import com.purui.prims.headless.api.pojo.response.SemanticQueryResp;
import com.purui.prims.headless.server.service.DataSetService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/api/semantic/query")
@Slf4j
@Api(tags = "数据集查询")
public class DataSetQueryApiController {

    @Autowired
    private DataSetService dataSetService;

    @ApiOperation(value = "根据条件查询")
    @PostMapping("/dataSet")
    public SemanticQueryResp queryByDataSet(@RequestBody QueryDataSetReq queryDataSetReq,
                                            HttpServletRequest request,
                                            HttpServletResponse response) throws Exception {
        User user = UserHolder.findUser(request, response);
        queryDataSetReq.setQueryType(QueryType.METRIC);
        return dataSetService.queryByDataSet(queryDataSetReq, user);
    }

    @ApiOperation(value = "获取BI查询使用的SQL")
    @GetMapping("/sql/dataset/{id}")
    public String buildSqlForBI(@PathVariable Long id) throws Exception {
        return dataSetService.buildAsSelectSql(id);
    }

}
