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

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

module.exports = class Room_typesDBApi {

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

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

        name: data.name
        ||
        null
            ,

        description: data.description
        ||
        null
            ,

        capacity: data.capacity
        ||
        null
            ,

        gender_policy: data.gender_policy
        ||
        null
            ,

        amenities_json: data.amenities_json
        ||
        null
            ,

        base_price: data.base_price
        ||
        null
            ,

        is_private: data.is_private
        ||
        false

            ,

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

        return room_types;
    }

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

                name: item.name
            ||
            null
            ,

                description: item.description
            ||
            null
            ,

                capacity: item.capacity
            ||
            null
            ,

                gender_policy: item.gender_policy
            ||
            null
            ,

                amenities_json: item.amenities_json
            ||
            null
            ,

                base_price: item.base_price
            ||
            null
            ,

                is_private: item.is_private
            ||
            false

            ,

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

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

        return room_types;
    }

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

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

        const updatePayload = {};

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

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

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

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

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

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

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

        updatePayload.updatedById = currentUser.id;

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

        return room_types;
    }

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

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

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

        return room_types;
    }

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

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

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

        await room_types.destroy({
            transaction
        });

        return room_types;
    }

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

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

        if (!room_types) {
            return room_types;
        }

        const output = room_types.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.name) {
                    where = {
                        ...where,
                        [Op.and]: Utils.ilike(
                            'room_types',
                            'name',
                            filter.name,
                        ),
                    };
                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

};

