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

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

module.exports = class Inventory_datesDBApi {

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

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

        date: data.date
        ||
        null
            ,

        alloted_beds: data.alloted_beds
        ||
        null
            ,

        closed_for_arrival: data.closed_for_arrival
        ||
        false

            ,

        closed_for_departure: data.closed_for_departure
        ||
        false

            ,

        override_price: data.override_price
        ||
        null
            ,

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

        return inventory_dates;
    }

    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 inventory_datesData = data.map((item, index) => ({
                id: item.id || undefined,

                date: item.date
            ||
            null
            ,

                alloted_beds: item.alloted_beds
            ||
            null
            ,

                closed_for_arrival: item.closed_for_arrival
            ||
            false

            ,

                closed_for_departure: item.closed_for_departure
            ||
            false

            ,

                override_price: item.override_price
            ||
            null
            ,

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

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

        return inventory_dates;
    }

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

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

        const updatePayload = {};

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

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

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

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

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

        updatePayload.updatedById = currentUser.id;

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

        return inventory_dates;
    }

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

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

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

        return inventory_dates;
    }

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

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

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

        await inventory_dates.destroy({
            transaction
        });

        return inventory_dates;
    }

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

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

        if (!inventory_dates) {
            return inventory_dates;
        }

        const output = inventory_dates.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.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.alloted_bedsRange) {
                const [start, end] = filter.alloted_bedsRange;

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

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

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

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

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

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

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

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

            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.inventory_dates.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(
                        'inventory_dates',
                        'date',
                        query,
                    ),
                ],
            };
        }

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

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

};

