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

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

module.exports = class ShareholdersDBApi {

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

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

        name_en: data.name_en
        ||
        null
            ,

        name_kh: data.name_kh
        ||
        null
            ,

        earn_rate: data.earn_rate
        ||
        null
            ,

        date_of_birth: data.date_of_birth
        ||
        null
            ,

        phone_number: data.phone_number
        ||
        null
            ,

        start_work_date: data.start_work_date
        ||
        null
            ,

        born_place: data.born_place
        ||
        null
            ,

        document_type: data.document_type
        ||
        null
            ,

        document_number: data.document_number
        ||
        null
            ,

        emergency_number: data.emergency_number
        ||
        null
            ,

        current_place: data.current_place
        ||
        null
            ,

        sex: data.sex
        ||
        null
            ,

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

        return shareholders;
    }

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

                name_en: item.name_en
            ||
            null
            ,

                name_kh: item.name_kh
            ||
            null
            ,

                earn_rate: item.earn_rate
            ||
            null
            ,

                date_of_birth: item.date_of_birth
            ||
            null
            ,

                phone_number: item.phone_number
            ||
            null
            ,

                start_work_date: item.start_work_date
            ||
            null
            ,

                born_place: item.born_place
            ||
            null
            ,

                document_type: item.document_type
            ||
            null
            ,

                document_number: item.document_number
            ||
            null
            ,

                emergency_number: item.emergency_number
            ||
            null
            ,

                current_place: item.current_place
            ||
            null
            ,

                sex: item.sex
            ||
            null
            ,

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

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

        return shareholders;
    }

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

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

        const updatePayload = {};

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

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

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

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

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

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

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

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

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

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

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

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

        updatePayload.updatedById = currentUser.id;

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

        return shareholders;
    }

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

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

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

        return shareholders;
    }

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

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

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

        await shareholders.destroy({
            transaction
        });

        return shareholders;
    }

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

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

        if (!shareholders) {
            return shareholders;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

};

