"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
const { MetadataTypes } = require("../../constants");
const { generateMetadataID } = require("../../db/utils");
const { saveEntityMetadata, deleteEntityMetadata } = require("../../utilities");
const { getAppDB } = require("@devlego/backend-core/context");
exports.getTypes = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    ctx.body = {
        types: MetadataTypes,
    };
});
exports.saveMetadata = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    const { type, entityId } = ctx.params;
    if (type === MetadataTypes.AUTOMATION_TEST_HISTORY) {
        ctx.throw(400, "Cannot save automation history type");
    }
    ctx.body = yield saveEntityMetadata(type, entityId, ctx.request.body);
});
exports.deleteMetadata = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    const { type, entityId } = ctx.params;
    yield deleteEntityMetadata(type, entityId);
    ctx.body = {
        message: "Metadata deleted successfully",
    };
});
exports.getMetadata = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    const { type, entityId } = ctx.params;
    const db = getAppDB();
    const id = generateMetadataID(type, entityId);
    try {
        ctx.body = yield db.get(id);
    }
    catch (err) {
        if (err.status === 404) {
            ctx.body = {};
        }
        else {
            ctx.throw(err.status, err);
        }
    }
});
