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

module.exports = Self => {
    Self.remoteMethodCtx('canEdit', {
        description: 'Check if all the received sales are aditable',
        accessType: 'READ',
        accepts: [{
            arg: 'sales',
            type: ['number'],
            required: true
        }],
        returns: {
            type: 'boolean',
            root: true
        },
        http: {
            path: `/canEdit`,
            verb: 'GET'
        }
    });

    Self.canEdit = async(ctx, sales, options) => {
        const models = Self.app.models;
        const myOptions = {};

        if (typeof options == 'object')
            Object.assign(myOptions, options);

        const salesData = await models.Sale.find({
            fields: ['id', 'itemFk', 'ticketFk'],
            where: {id: {inq: sales}},
            include:
            {
                relation: 'item',
                scope: {
                    fields: ['id', 'isFloramondo'],
                }
            }
        }, myOptions);

        if (!salesData.length)
            throw new UserError(`The sales do not exists`);

        const ticketId = salesData[0].ticketFk;

        const isTicketEditable = await models.Ticket.isEditable(ctx, ticketId, myOptions);
        if (!isTicketEditable)
            throw new UserError(`The sales of this ticket can't be modified`);

        const hasSaleTracking = await models.SaleTracking.findOne({where: {saleFk: {inq: sales}}}, myOptions);
        const hasSaleCloned = await models.SaleCloned.findOne({where: {saleClonedFk: {inq: sales}}}, myOptions);
        const hasSaleFloramondo = salesData.find(sale => sale.item().isFloramondo);

        const canEditTracked = await models.ACL.checkAccessAcl(ctx, 'Sale', 'editTracked');
        const canEditCloned = await models.ACL.checkAccessAcl(ctx, 'Sale', 'editCloned');
        const canEditFloramondo = await models.ACL.checkAccessAcl(ctx, 'Sale', 'editFloramondo');

        const shouldEditTracked = canEditTracked || !hasSaleTracking;
        const shouldEditCloned = canEditCloned || !hasSaleCloned;
        const shouldEditFloramondo = canEditFloramondo || !hasSaleFloramondo;

        if (!shouldEditTracked)
            throw new UserError('It is not possible to modify tracked sales');
        if (!shouldEditCloned)
            throw new UserError('It is not possible to modify cloned sales');
        if (!shouldEditFloramondo)
            throw new UserError('It is not possible to modify sales that their articles are from Floramondo');
    };
};