"use strict";

const Promise = require("bluebird");
const { chain } = require("error-chain");

const mmAxios = require("@modular-matrix/axios");
const matchProtocolError = require("@modular-matrix/match-protocol-error");
const errors = require("@modular-matrix/errors");
const getUploadSizeLimit = require("../get-upload-size-limit");
const getFilesize = require("../get-filesize");

const { validateArguments } = require("@validatem/core");
const required = require("@validatem/required");
const isString = require("@validatem/is-string");
const isSession = require("@modular-matrix/is-session");

module.exports = function uploadFile(_session, _options) {
	let [ session, options ] = validateArguments(arguments, {
		session: [ required, isSession ],
		options: [ required, {
			filename: [ isString ],
			file: [ required ], // FIXME: Stream or blob or buffer or string
		}]
	});

	let axios = mmAxios({ session });

	return Promise.all([
		getUploadSizeLimit(session),
		getFilesize(options.file)
	]).then(([ sizeLimit, filesize ]) => {
		if (sizeLimit == null || filesize <= sizeLimit.limit) {
			return axios.post("/media/r0/upload", options.file, {
				params: options.filename != null
					? { filename: options.filename }
					: undefined
			});
		} else {
			throw new errors.FilesizeLimitExceeded("The file will exceed the upload filesize limit for this server", { limit: sizeLimit });
		}
	}).then((response) => {
		return { url: response.data.content_uri };
	}).catch(matchProtocolError(403, "M_FORBIDDEN"), (error) => {
		throw chain(error, errors.AccessDenied, "The uploaded file was rejected");
	}).catch(matchProtocolError(413, "M_TOO_LARGE"), (error) => {
		throw chain(error, errors.FilesizeLimitExceeded, "The uploaded file exceeds the filesize limit for this server", { limit: undefined });
	});
};
