"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleRemoteCopy = handleRemoteCopy;
const some_1 = __importDefault(require("lodash/some"));
// @ts-ignore
const javascript_wrapper_1 = __importDefault(require("@ytsaurus/javascript-wrapper"));
const utils_1 = require("../utils");
const utils_2 = require("../components/utils");
const yt = (0, javascript_wrapper_1.default)();
async function handleRemoteCopy(req, res) {
    await req.ctx.call(`RemoteCopy ${req.id}`, async (ctx) => {
        function sendErrorAndLog(title, error, statusCode = null) {
            ctx.logError(title || 'Error', error);
            (0, utils_1.sendAndLogError)(ctx, res, statusCode, error);
        }
        ctx.log('Begin', req.body);
        try {
            const body = req.body || {};
            const { [body.cluster_name]: srcClusterConfig, [body.dstCluster]: dstClusterConfig } = (0, utils_2.getClustersFromConfig)();
            if (!srcClusterConfig) {
                return sendErrorAndLog('Wrong params', new Error('Unexpected value of "cluster_name"'), 400);
            }
            if (!dstClusterConfig) {
                return sendErrorAndLog('Wrong params', new Error('Unexpected value of "dstCluster"'), 400);
            }
            if (!Array.isArray(body.input_table_paths) ||
                (0, some_1.default)(body.input_table_paths, (item) => 'string' !== typeof item)) {
                return sendErrorAndLog('Wrong params', new Error('"input_table_paths" should be defined as an array of string'), 400);
            }
            if ('string' !== typeof body.output_table_path) {
                return sendErrorAndLog('Wrong params', new Error('"output_table_path" should be defined as a string'), 400);
            }
            const { ytApiAuthHeaders } = req.yt;
            const { 
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            dstCluster, override, ...spec } = req.body;
            const setup = {
                requestHeaders: ytApiAuthHeaders,
                proxy: `${dstClusterConfig.proxy}`,
            };
            const existPromise = override
                ? Promise.resolve(false)
                : yt.v3.exists({ setup, parameters: { path: body.output_table_path } });
            return existPromise.then((value) => {
                if (value) {
                    return sendErrorAndLog(`Path already exists.`, new Error(`"${body.output_table_path}" path already exist.`), 409);
                }
                return yt.v3
                    .remoteCopy({
                    setup,
                    parameters: {
                        spec: {
                            ...spec,
                            output_table_path: {
                                $value: body.output_table_path,
                                $attributes: { create: true },
                            },
                        },
                    },
                })
                    .then((response) => {
                    res.status(200).send(response);
                })
                    .catch((e) => {
                    sendErrorAndLog('Error in yt.v3.remoteCopy', e);
                });
            });
        }
        catch (e) {
            sendErrorAndLog('Unexpected error', e);
        }
        ctx.log('End');
    });
}
