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

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

module.exports = class CouponsDBApi {

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

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

        code: data.code
        ||
        null
            ,

        type: data.type
        ||
        null
            ,

        value: data.value
        ||
        null
            ,

        currency: data.currency
        ||
        null
            ,

        starts_at: data.starts_at
        ||
        null
            ,

        ends_at: data.ends_at
        ||
        null
            ,

        max_redemptions: data.max_redemptions
        ||
        null
            ,

        times_redeemed: data.times_redeemed
        ||
        null
            ,

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

        return coupons;
    }

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

                code: item.code
            ||
            null
            ,

                type: item.type
            ||
            null
            ,

                value: item.value
            ||
            null
            ,

                currency: item.currency
            ||
            null
            ,

                starts_at: item.starts_at
            ||
            null
            ,

                ends_at: item.ends_at
            ||
            null
            ,

                max_redemptions: item.max_redemptions
            ||
            null
            ,

                times_redeemed: item.times_redeemed
            ||
            null
            ,

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

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

        return coupons;
    }

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

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

        const updatePayload = {};

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

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

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

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

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

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

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

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

        updatePayload.updatedById = currentUser.id;

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

        return coupons;
    }

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

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

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

        return coupons;
    }

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

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

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

        await coupons.destroy({
            transaction
        });

        return coupons;
    }

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

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

        if (!coupons) {
            return coupons;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

};

