import {
  Body,
  Controller,
  Delete,
  Get,
  Patch,
  Path,
  Post,
  Query,
  Request,
  Route,
  Security,
  Tags,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success";
import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import { RequestWithUser } from "../middlewares/user";
import { MetaWorkflow } from "../entities/MetaWorkflow";
import { MetaState } from "../entities/MetaState";
import { MetaStateOperator } from "../entities/MetaStateOperator";
@Route("api/v1/org/view-workflow")
@Tags("View Workflow")
@Security("bearerAuth")
export class ViewWorkFlowController extends Controller {
  private metaWorkflowRepository = AppDataSource.getRepository(MetaWorkflow);
  private metaStateRepository = AppDataSource.getRepository(MetaState);
  private metaStateOperatorRepository = AppDataSource.getRepository(MetaStateOperator);

  @Get("lists")
  public async getSystems(@Request() req: RequestWithUser) {
    const lists = await this.metaWorkflowRepository
      .createQueryBuilder("metaWorkflow")
      .select(["metaWorkflow.name", "metaWorkflow.sysName"])
      // .groupBy("metaWorkflow.name")
      .getMany();

    const sys: any = [];

    for (let index = 0; index < lists.length; index++) {
      const element = await lists[index];
      if (sys.findIndex((x: any) => x.sysName === element.sysName) === -1) {
        sys.push({
          sysName: element.sysName,
          name: element.name,
        });
      }
    }

    return new HttpSuccess(sys);
  }

  @Get("")
  public async getLists(
    @Request() req: RequestWithUser,
    @Query("sysName") sysName: string,
    @Query("posTypeName") posTypeName: string,
    @Query("posLevelName") posLevelName: string,
  ) {
    const lists = await this.metaWorkflowRepository.find({
      select: ["id", "name", "sysName", "posTypeName", "posLevelName"],
      where: { sysName: sysName, posTypeName: posTypeName, posLevelName: posLevelName },
      relations: ["metaStates", "metaStates.metaStateOperators"],
      order: {
        metaStates: {
          order: "ASC",
        },
      },
    });
    return new HttpSuccess(lists);
  }
}
