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



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

module.exports = class Gdpr_consentsDBApi {
    

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

        const gdpr_consents = await db.gdpr_consents.create(
            {
                id: data.id || undefined,
        
        terms_accepted: data.terms_accepted
        ||
        false
        
            ,
            
        terms_accepted_at: data.terms_accepted_at
        ||
        null
            ,
            
        privacy_policy_accepted: data.privacy_policy_accepted
        ||
        false
        
            ,
            
        privacy_policy_accepted_at: data.privacy_policy_accepted_at
        ||
        null
            ,
            
        marketing_emails_opt_in: data.marketing_emails_opt_in
        ||
        false
        
            ,
            
        marketing_opt_in_at: data.marketing_opt_in_at
        ||
        null
            ,
            
        consent_source: data.consent_source
        ||
        null
            ,
            
        consent_version: data.consent_version
        ||
        null
            ,
            
        ip_address: data.ip_address
        ||
        null
            ,
            
        user_agent: data.user_agent
        ||
        null
            ,
            
        lawful_basis: data.lawful_basis
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return gdpr_consents;
    }
    

    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 gdpr_consentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                terms_accepted: item.terms_accepted
            ||
            false
        
            ,
            
                terms_accepted_at: item.terms_accepted_at
            ||
            null
            ,
            
                privacy_policy_accepted: item.privacy_policy_accepted
            ||
            false
        
            ,
            
                privacy_policy_accepted_at: item.privacy_policy_accepted_at
            ||
            null
            ,
            
                marketing_emails_opt_in: item.marketing_emails_opt_in
            ||
            false
        
            ,
            
                marketing_opt_in_at: item.marketing_opt_in_at
            ||
            null
            ,
            
                consent_source: item.consent_source
            ||
            null
            ,
            
                consent_version: item.consent_version
            ||
            null
            ,
            
                ip_address: item.ip_address
            ||
            null
            ,
            
                user_agent: item.user_agent
            ||
            null
            ,
            
                lawful_basis: item.lawful_basis
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return gdpr_consents;
    }

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

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


        

        const updatePayload = {};
        
        if (data.terms_accepted !== undefined) updatePayload.terms_accepted = data.terms_accepted;
        
        
        if (data.terms_accepted_at !== undefined) updatePayload.terms_accepted_at = data.terms_accepted_at;
        
        
        if (data.privacy_policy_accepted !== undefined) updatePayload.privacy_policy_accepted = data.privacy_policy_accepted;
        
        
        if (data.privacy_policy_accepted_at !== undefined) updatePayload.privacy_policy_accepted_at = data.privacy_policy_accepted_at;
        
        
        if (data.marketing_emails_opt_in !== undefined) updatePayload.marketing_emails_opt_in = data.marketing_emails_opt_in;
        
        
        if (data.marketing_opt_in_at !== undefined) updatePayload.marketing_opt_in_at = data.marketing_opt_in_at;
        
        
        if (data.consent_source !== undefined) updatePayload.consent_source = data.consent_source;
        
        
        if (data.consent_version !== undefined) updatePayload.consent_version = data.consent_version;
        
        
        if (data.ip_address !== undefined) updatePayload.ip_address = data.ip_address;
        
        
        if (data.user_agent !== undefined) updatePayload.user_agent = data.user_agent;
        
        
        if (data.lawful_basis !== undefined) updatePayload.lawful_basis = data.lawful_basis;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return gdpr_consents;
    }

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

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

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


        return gdpr_consents;
    }

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

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

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

        await gdpr_consents.destroy({
            transaction
        });

        return gdpr_consents;
    }

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

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

        if (!gdpr_consents) {
            return gdpr_consents;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.guests_gdpr_consent = await gdpr_consents.getGuests_gdpr_consent({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        return output;
    }

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

        

        

        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.consent_version) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'gdpr_consents',
                        'consent_version',
                        filter.consent_version,
                    ),
                };
            }
            
            if (filter.ip_address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'gdpr_consents',
                        'ip_address',
                        filter.ip_address,
                    ),
                };
            }
            
            if (filter.user_agent) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'gdpr_consents',
                        'user_agent',
                        filter.user_agent,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    terms_accepted_at: {
                    ...where.terms_accepted_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.privacy_policy_accepted_atRange) {
                const [start, end] = filter.privacy_policy_accepted_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    privacy_policy_accepted_at: {
                    ...where.privacy_policy_accepted_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.marketing_opt_in_atRange) {
                const [start, end] = filter.marketing_opt_in_atRange;

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

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

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

            
            if (filter.terms_accepted) {
                where = {
                    ...where,
                terms_accepted: filter.terms_accepted,
            };
            }
            
            if (filter.privacy_policy_accepted) {
                where = {
                    ...where,
                privacy_policy_accepted: filter.privacy_policy_accepted,
            };
            }
            
            if (filter.marketing_emails_opt_in) {
                where = {
                    ...where,
                marketing_emails_opt_in: filter.marketing_emails_opt_in,
            };
            }
            
            if (filter.consent_source) {
                where = {
                    ...where,
                consent_source: filter.consent_source,
            };
            }
            
            if (filter.lawful_basis) {
                where = {
                    ...where,
                lawful_basis: filter.lawful_basis,
            };
            }
            




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

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

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

    
};

