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

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

module.exports = class CampaignsDBApi {

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

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

        name: data.name
        ||
        null
            ,

        status: data.status
        ||
        null
            ,

        campaign_number: data.campaign_number
        ||
        null
            ,

        thyme_campaign_number: data.thyme_campaign_number
        ||
        null
            ,

        campaign_name: data.campaign_name
        ||
        null
            ,

        scheduled_completion_date: data.scheduled_completion_date
        ||
        null
            ,

        billing_status: data.billing_status
        ||
        null
            ,

        total_cost: data.total_cost
        ||
        null
            ,

        total_invoiced: data.total_invoiced
        ||
        null
            ,

        uninvoiced: data.uninvoiced
        ||
        null
            ,

        remaining_invoice_decimal: data.remaining_invoice_decimal
        ||
        null
            ,

        timing_project_id: data.timing_project_id
        ||
        null
            ,

        timing_app_department_id: data.timing_app_department_id
        ||
        null
            ,

        timing_id: data.timing_id
        ||
        null
            ,

        client_details: data.client_details
        ||
        null
            ,

        sub_brand: data.sub_brand
        ||
        null
            ,

        start_date: data.start_date
        ||
        null
            ,

        admin_override: data.admin_override
        ||
        false

            ,

        current_date: data.current_date
        ||
        null
            ,

        contact_info: data.contact_info
        ||
        null
            ,

        client_contact: data.client_contact
        ||
        null
            ,

        country: data.country
        ||
        null
            ,

        language: data.language
        ||
        null
            ,

        client_ref: data.client_ref
        ||
        null
            ,

        client_job_number: data.client_job_number
        ||
        null
            ,

        invoice_number: data.invoice_number
        ||
        null
            ,

        revenue_code: data.revenue_code
        ||
        null
            ,

        created_date: data.created_date
        ||
        null
            ,

        last_updated_date: data.last_updated_date
        ||
        null
            ,

        timing_app: data.timing_app
        ||
        null
            ,

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

        return campaigns;
    }

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

                name: item.name
            ||
            null
            ,

                status: item.status
            ||
            null
            ,

                campaign_number: item.campaign_number
            ||
            null
            ,

                thyme_campaign_number: item.thyme_campaign_number
            ||
            null
            ,

                campaign_name: item.campaign_name
            ||
            null
            ,

                scheduled_completion_date: item.scheduled_completion_date
            ||
            null
            ,

                billing_status: item.billing_status
            ||
            null
            ,

                total_cost: item.total_cost
            ||
            null
            ,

                total_invoiced: item.total_invoiced
            ||
            null
            ,

                uninvoiced: item.uninvoiced
            ||
            null
            ,

                remaining_invoice_decimal: item.remaining_invoice_decimal
            ||
            null
            ,

                timing_project_id: item.timing_project_id
            ||
            null
            ,

                timing_app_department_id: item.timing_app_department_id
            ||
            null
            ,

                timing_id: item.timing_id
            ||
            null
            ,

                client_details: item.client_details
            ||
            null
            ,

                sub_brand: item.sub_brand
            ||
            null
            ,

                start_date: item.start_date
            ||
            null
            ,

                admin_override: item.admin_override
            ||
            false

            ,

                current_date: item.current_date
            ||
            null
            ,

                contact_info: item.contact_info
            ||
            null
            ,

                client_contact: item.client_contact
            ||
            null
            ,

                country: item.country
            ||
            null
            ,

                language: item.language
            ||
            null
            ,

                client_ref: item.client_ref
            ||
            null
            ,

                client_job_number: item.client_job_number
            ||
            null
            ,

                invoice_number: item.invoice_number
            ||
            null
            ,

                revenue_code: item.revenue_code
            ||
            null
            ,

                created_date: item.created_date
            ||
            null
            ,

                last_updated_date: item.last_updated_date
            ||
            null
            ,

                timing_app: item.timing_app
            ||
            null
            ,

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

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

        return campaigns;
    }

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

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

        const updatePayload = {};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        updatePayload.updatedById = currentUser.id;

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

        return campaigns;
    }

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

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

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

        return campaigns;
    }

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

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

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

        await campaigns.destroy({
            transaction
        });

        return campaigns;
    }

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

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

        if (!campaigns) {
            return campaigns;
        }

        const output = campaigns.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(
                            'campaigns',
                            'name',
                            filter.name,
                        ),
                    };
                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

};

