const UserError = require('vn-loopback/util/user-error');
const fs = require('fs/promises');
const path = require('path');

module.exports = Self => {
    Self.remoteMethodCtx('upload', {
        description: 'Uploads a file and inserts into dms model',
        accessType: 'WRITE',
        accepts: [
            {
                arg: 'id',
                type: 'Number',
                description: 'The entity id',
                required: true
            }, {
                arg: 'collection',
                type: 'string',
                description: 'The collection name',
                required: true
            }
        ],
        returns: {
            type: 'Object',
            root: true
        },
        http: {
            path: `/upload`,
            verb: 'POST'
        }
    });

    Self.upload = async ctx => {
        const models = Self.app.models;
        const TempContainer = models.TempContainer;
        const fileOptions = {};
        const args = ctx.args;

        let tempFilePath;
        try {
            const hasWriteRole = await models.ImageCollection.hasWriteRole(ctx, args.collection);
            if (!hasWriteRole)
                throw new UserError(`You don't have enough privileges`);

            if (process.env.NODE_ENV == 'test')
                throw new UserError(`Action not allowed on the test environment`);

            // Upload file to temporary path
            const tempContainer = await TempContainer.container(args.collection);
            const uploaded = await TempContainer.upload(tempContainer.name, ctx.req, ctx.result, fileOptions);
            const [uploadedFile] = Object.values(uploaded.files).map(file => {
                return file[0];
            });

            const file = await TempContainer.getFile(tempContainer.name, uploadedFile.name);
            tempFilePath = path.join(file.client.root, file.container, file.name);

            const fileName = `${args.id}.png`;

            await models.Image.resize({
                collectionName: args.collection,
                srcFile: tempFilePath,
                fileName: fileName,
                entityId: args.id
            });
        } finally {
            try {
                await fs.unlink(tempFilePath);
            } catch (error) { }
        }
    };
};