var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import ComponentCode from "../../ComponentCode";
import BaseModel from "../../../../../Models/DatabaseModels/DatabaseBaseModel/DatabaseBaseModel";
import BadDataException from "../../../../../Types/Exception/BadDataException";
import JSONFunctions from "../../../../../Types/JSONFunctions";
import Text from "../../../../../Types/Text";
import BaseModelComponents from "../../../../../Types/Workflow/Components/BaseModel";
import CaptureSpan from "../../../../Utils/Telemetry/CaptureSpan";
export default class FindOneBaseModel extends ComponentCode {
    constructor(modelService) {
        super();
        this.modelService = null;
        const BaseModelComponent = BaseModelComponents.getComponents(modelService.getModel()).find((i) => {
            return (i.id ===
                `${Text.pascalCaseToDashes(modelService.getModel().tableName)}-find-one`);
        });
        if (!BaseModelComponent) {
            throw new BadDataException("Find one component for " +
                modelService.getModel().tableName +
                " not found.");
        }
        this.setMetadata(BaseModelComponent);
        this.modelService = modelService;
    }
    async run(args, options) {
        const successPort = this.getMetadata().outPorts.find((p) => {
            return p.id === "success";
        });
        if (!successPort) {
            throw options.onError(new BadDataException("Success port not found"));
        }
        const errorPort = this.getMetadata().outPorts.find((p) => {
            return p.id === "error";
        });
        if (!errorPort) {
            throw options.onError(new BadDataException("Error port not found"));
        }
        try {
            if (!this.modelService) {
                throw options.onError(new BadDataException("modelService is undefined."));
            }
            if (!args["query"]) {
                throw options.onError(new BadDataException("Query is undefined."));
            }
            if (typeof args["query"] === "string") {
                args["query"] = JSONFunctions.parse(args["query"]);
            }
            if (typeof args["query"] !== "object") {
                throw options.onError(new BadDataException("Query is should be of type object."));
            }
            if (this.modelService.getModel().getTenantColumn()) {
                args["query"][this.modelService.getModel().getTenantColumn()] = options.projectId;
            }
            if (!args["select"]) {
                throw options.onError(new BadDataException("Select Fields is undefined."));
            }
            if (typeof args["select"] === "string") {
                args["select"] = JSONFunctions.parse(args["select"]);
            }
            if (typeof args["select"] !== "object") {
                throw options.onError(new BadDataException("Select Fields is should be of type object."));
            }
            let query = args["query"];
            if (query) {
                query = JSONFunctions.deserialize(args["query"]);
            }
            let select = args["select"];
            if (select) {
                select = JSONFunctions.deserialize(args["select"]);
            }
            const model = await this.modelService.findOneBy({
                query: query || {},
                select: select,
                props: {
                    isRoot: true,
                    tenantId: options.projectId,
                },
            });
            return {
                returnValues: {
                    model: model
                        ? BaseModel.toJSON(model, this.modelService.modelType)
                        : null,
                },
                executePort: successPort,
            };
        }
        catch (err) {
            options.log("Error running component");
            options.log(err.message ? err.message : JSON.stringify(err, null, 2));
            return {
                returnValues: {},
                executePort: errorPort,
            };
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", Promise)
], FindOneBaseModel.prototype, "run", null);
//# sourceMappingURL=FindOneBaseModel.js.map