module.exports = Self => {
    Self.remoteMethod('getByWarehouse', {
        description: 'Returns an array of labour holidays from an specified warehouse',
        accepts: [{
            arg: 'warehouseFk',
            type: 'Number',
            required: true,
        }],
        returns: {
            type: ['object'],
            root: true
        },
        http: {
            path: `/getByWarehouse`,
            verb: 'GET'
        }
    });

    Self.getByWarehouse = async warehouseFk => {
        let beginningYear = Date.vnNew();
        beginningYear.setMonth(0);
        beginningYear.setDate(1);
        beginningYear.setHours(0, 0, 0, 0);

        let holidays = await Self.rawSql(
            `SELECT clh.dated, chn.name, cht.name, w.id
                FROM vn.calendarHolidays clh
                    JOIN vn.workCenter w ON w.id = clh.workcenterFk
                    LEFT JOIN vn.calendarHolidaysName chn ON chn.id = clh.calendarHolidaysNameFk
                    LEFT JOIN vn.calendarHolidaysType cht ON cht.id = clh.calendarHolidaysTypeFk
                WHERE w.warehouseFk = ? AND clh.dated >= ?`, [warehouseFk, beginningYear]);

        return holidays.map(holiday => {
            holiday.dated = new Date(holiday.dated);
            holiday.dated.setHours(0, 0, 0, 0);

            return holiday;
        });
    };
};