"use strict";
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);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InstanceService = void 0;
const common_1 = require("@nestjs/common");
const mongoose_1 = require("@nestjs/mongoose");
const mongoose_2 = require("mongoose");
const bcryptjs_1 = require("bcryptjs");
const filters_1 = require("../utils/Filters/filters");
const form_schema_1 = require("../forms/schemas/form.schema");
const form_data_schema_1 = require("../formData/schemas/form-data.schema");
const instance_schema_1 = require("./schemas/instance.schema");
let InstanceService = class InstanceService {
    constructor(instanceModel, formModel, formDataModel) {
        this.instanceModel = instanceModel;
        this.formModel = formModel;
        this.formDataModel = formDataModel;
    }
    async create(createInstanceDto) {
        const hashedKey = await (0, bcryptjs_1.hash)(createInstanceDto.apikey, 10);
        return this.instanceModel.create({
            name: createInstanceDto.name,
            apikey: hashedKey
        });
    }
    async findAll(find) {
        let filter = {};
        try {
            filter = find.criteria ? (0, filters_1.filterConverter)(JSON.parse(find.criteria)) : {};
        }
        catch (e) {
        }
        const count = await this.instanceModel.countDocuments(filter).exec();
        const results = find.limit > 0
            ? await this.instanceModel.find(filter).skip(find.offset).limit(find.limit).exec()
            : [];
        return {
            offset: find.offset,
            count,
            results,
        };
    }
    findOne(id) {
        return this.instanceModel.findById(id).exec();
    }
    async findOneByNameAndKey(name, apikey) {
        const instances = await this.instanceModel.find({
            name
        }).exec();
        const result = instances.find((a) => {
            try {
                return (0, bcryptjs_1.compareSync)(apikey, a.apikey);
            }
            catch (_a) {
                return false;
            }
        });
        if (!result) {
            throw new common_1.NotFoundException('Could not find instance by apikey');
        }
        return result;
    }
    async update(id, updateInstanceDto) {
        const hashedKey = await (0, bcryptjs_1.hash)(updateInstanceDto.apikey, 10);
        return this.instanceModel
            .findByIdAndUpdate(id, {
            name: updateInstanceDto.name,
            apikey: hashedKey
        }, { new: true })
            .exec();
    }
    async remove(id) {
        const formsResult = await this.formModel.find({ instance: id }).exec();
        await Promise.all(formsResult.map(form => this.formDataModel.deleteMany({ form: form._id })));
        await this.formModel.deleteMany({ instance: id });
        return this.instanceModel.findByIdAndDelete(id).exec();
    }
};
exports.InstanceService = InstanceService;
exports.InstanceService = InstanceService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, mongoose_1.InjectModel)(instance_schema_1.Instance.name)),
    __param(1, (0, mongoose_1.InjectModel)(form_schema_1.Form.name)),
    __param(2, (0, mongoose_1.InjectModel)(form_data_schema_1.FormData.name)),
    __metadata("design:paramtypes", [mongoose_2.Model,
        mongoose_2.Model,
        mongoose_2.Model])
], InstanceService);
//# sourceMappingURL=instance.service.js.map