"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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.exportRows = exports.fetchEnrichedRow = exports.validate = exports.search = exports.destroy = exports.find = exports.fetch = exports.fetchView = exports.save = exports.patch = void 0;
const pro_1 = require("@devlego/pro");
const internal_1 = __importDefault(require("./internal"));
const external_1 = __importDefault(require("./external"));
const utils_1 = require("../../../integrations/utils");
function pickApi(tableId) {
    if ((0, utils_1.isExternalTable)(tableId)) {
        return external_1.default;
    }
    return internal_1.default;
}
function getTableId(ctx) {
    if (ctx.request.body && ctx.request.body.tableId) {
        return ctx.request.body.tableId;
    }
    if (ctx.params && ctx.params.tableId) {
        return ctx.params.tableId;
    }
    if (ctx.params && ctx.params.viewName) {
        return ctx.params.viewName;
    }
}
function patch(ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        const appId = ctx.appId;
        const tableId = getTableId(ctx);
        const body = ctx.request.body;
        // if it doesn't have an _id then its save
        if (body && !body._id) {
            return (0, exports.save)(ctx);
        }
        try {
            const { row, table } = yield pro_1.quotas.addQuery(() => pickApi(tableId).patch(ctx));
            ctx.status = 200;
            ctx.eventEmitter &&
                ctx.eventEmitter.emitRow(`row:update`, appId, row, table);
            ctx.message = `${table.name} updated successfully.`;
            ctx.body = row;
        }
        catch (err) {
            ctx.throw(400, err);
        }
    });
}
exports.patch = patch;
const save = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    const appId = ctx.appId;
    const tableId = getTableId(ctx);
    const body = ctx.request.body;
    // if it has an ID already then its a patch
    if (body && body._id) {
        return patch(ctx);
    }
    try {
        const { row, table } = yield pro_1.quotas.addRow(() => pro_1.quotas.addQuery(() => pickApi(tableId).save(ctx)));
        ctx.status = 200;
        ctx.eventEmitter && ctx.eventEmitter.emitRow(`row:save`, appId, row, table);
        ctx.message = `${table.name} saved successfully`;
        ctx.body = row;
    }
    catch (err) {
        ctx.throw(400, err);
    }
});
exports.save = save;
function fetchView(ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        const tableId = getTableId(ctx);
        try {
            ctx.body = yield pro_1.quotas.addQuery(() => pickApi(tableId).fetchView(ctx));
        }
        catch (err) {
            ctx.throw(400, err);
        }
    });
}
exports.fetchView = fetchView;
function fetch(ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        const tableId = getTableId(ctx);
        try {
            ctx.body = yield pro_1.quotas.addQuery(() => pickApi(tableId).fetch(ctx));
        }
        catch (err) {
            ctx.throw(400, err);
        }
    });
}
exports.fetch = fetch;
function find(ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        const tableId = getTableId(ctx);
        try {
            ctx.body = yield pro_1.quotas.addQuery(() => pickApi(tableId).find(ctx));
        }
        catch (err) {
            ctx.throw(400, err);
        }
    });
}
exports.find = find;
function destroy(ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        const appId = ctx.appId;
        const inputs = ctx.request.body;
        const tableId = getTableId(ctx);
        let response, row;
        if (inputs.rows) {
            let { rows } = yield pro_1.quotas.addQuery(() => pickApi(tableId).bulkDestroy(ctx));
            yield pro_1.quotas.removeRows(rows.length);
            response = rows;
            for (let row of rows) {
                ctx.eventEmitter && ctx.eventEmitter.emitRow(`row:delete`, appId, row);
            }
        }
        else {
            let resp = yield pro_1.quotas.addQuery(() => pickApi(tableId).destroy(ctx));
            yield pro_1.quotas.removeRow();
            response = resp.response;
            row = resp.row;
            ctx.eventEmitter && ctx.eventEmitter.emitRow(`row:delete`, appId, row);
        }
        ctx.status = 200;
        // for automations include the row that was deleted
        ctx.row = row || {};
        ctx.body = response;
    });
}
exports.destroy = destroy;
function search(ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        const tableId = getTableId(ctx);
        try {
            ctx.status = 200;
            ctx.body = yield pro_1.quotas.addQuery(() => pickApi(tableId).search(ctx));
        }
        catch (err) {
            ctx.throw(400, err);
        }
    });
}
exports.search = search;
function validate(ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        const tableId = getTableId(ctx);
        try {
            ctx.body = yield pickApi(tableId).validate(ctx);
        }
        catch (err) {
            ctx.throw(400, err);
        }
    });
}
exports.validate = validate;
function fetchEnrichedRow(ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        const tableId = getTableId(ctx);
        try {
            ctx.body = yield pro_1.quotas.addQuery(() => pickApi(tableId).fetchEnrichedRow(ctx));
        }
        catch (err) {
            ctx.throw(400, err);
        }
    });
}
exports.fetchEnrichedRow = fetchEnrichedRow;
const exportRows = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    const tableId = getTableId(ctx);
    try {
        ctx.body = yield pro_1.quotas.addQuery(() => pickApi(tableId).exportRows(ctx));
    }
    catch (err) {
        ctx.throw(400, err);
    }
});
exports.exportRows = exportRows;
