
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');

const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class CalendarsDBApi {

    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const calendars = await db.calendars.create(
            {
                id: data.id || undefined,

        date: data.date
        ||
        null
            ,

        is_weekend: data.is_weekend
        ||
        false

            ,

        is_holiday: data.is_holiday
        ||
        false

            ,

        description: data.description
        ||
        null
            ,

        flag: data.flag
        ||
        null
            ,

            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        return calendars;
    }

    static async bulkImport(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        // Prepare data - wrapping individual data transformations in a map() method
        const calendarsData = data.map((item, index) => ({
                id: item.id || undefined,

                date: item.date
            ||
            null
            ,

                is_weekend: item.is_weekend
            ||
            false

            ,

                is_holiday: item.is_holiday
            ||
            false

            ,

                description: item.description
            ||
            null
            ,

                flag: item.flag
            ||
            null
            ,

            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const calendars = await db.calendars.bulkCreate(calendarsData, { transaction });

        return calendars;
    }

    static async update(id, data, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const calendars = await db.calendars.findByPk(id, {}, {transaction});

        const updatePayload = {};

        if (data.date !== undefined) updatePayload.date = data.date;

        if (data.is_weekend !== undefined) updatePayload.is_weekend = data.is_weekend;

        if (data.is_holiday !== undefined) updatePayload.is_holiday = data.is_holiday;

        if (data.description !== undefined) updatePayload.description = data.description;

        if (data.flag !== undefined) updatePayload.flag = data.flag;

        updatePayload.updatedById = currentUser.id;

        await calendars.update(updatePayload, {transaction});

        return calendars;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const calendars = await db.calendars.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of calendars) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of calendars) {
                await record.destroy({transaction});
            }
        });

        return calendars;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const calendars = await db.calendars.findByPk(id, options);

        await calendars.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await calendars.destroy({
            transaction
        });

        return calendars;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const calendars = await db.calendars.findOne(
            { where },
            { transaction },
        );

        if (!calendars) {
            return calendars;
        }

        const output = calendars.get({plain: true});

        return output;
    }

    static async findAll(filter, options) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        const user = (options && options.currentUser) || null;

        offset = currentPage * limit;

        const orderBy = null;

        const transaction = (options && options.transaction) || undefined;

        let include = [];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

                if (filter.description) {
                    where = {
                        ...where,
                        [Op.and]: Utils.ilike(
                            'calendars',
                            'description',
                            filter.description,
                        ),
                    };
                }

                if (filter.flag) {
                    where = {
                        ...where,
                        [Op.and]: Utils.ilike(
                            'calendars',
                            'flag',
                            filter.flag,
                        ),
                    };
                }

            if (filter.dateRange) {
                const [start, end] = filter.dateRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    date: {
                    ...where.date,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    date: {
                    ...where.date,
                            [Op.lte]: end,
                    },
                };
                }
            }

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            if (filter.is_weekend) {
                where = {
                    ...where,
                is_weekend: filter.is_weekend,
            };
            }

            if (filter.is_holiday) {
                where = {
                    ...where,
                is_holiday: filter.is_holiday,
            };
            }

            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.calendars.findAndCountAll(queryOptions);

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset) {
        let where = {};

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'calendars',
                        'description',
                        query,
                    ),
                ],
            };
        }

        const records = await db.calendars.findAll({
            attributes: [ 'id', 'description' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            orderBy: [['description', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.description,
        }));
    }

};

