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

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

module.exports = class GuarantorDBApi {

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

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

        full_name: data.full_name
        ||
        null
            ,

        sex: data.sex
        ||
        null
            ,

        date_of_birth: data.date_of_birth
        ||
        null
            ,

        document_type: data.document_type
        ||
        null
            ,

        document_number: data.document_number
        ||
        null
            ,

        phone_number: data.phone_number
        ||
        null
            ,

        full_address_input: data.full_address_input
        ||
        null
            ,

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

        return guarantor;
    }

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

                full_name: item.full_name
            ||
            null
            ,

                sex: item.sex
            ||
            null
            ,

                date_of_birth: item.date_of_birth
            ||
            null
            ,

                document_type: item.document_type
            ||
            null
            ,

                document_number: item.document_number
            ||
            null
            ,

                phone_number: item.phone_number
            ||
            null
            ,

                full_address_input: item.full_address_input
            ||
            null
            ,

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

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

        return guarantor;
    }

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

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

        const updatePayload = {};

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

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

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

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

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

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

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

        updatePayload.updatedById = currentUser.id;

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

        return guarantor;
    }

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

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

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

        return guarantor;
    }

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

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

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

        await guarantor.destroy({
            transaction
        });

        return guarantor;
    }

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

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

        if (!guarantor) {
            return guarantor;
        }

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

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

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

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

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

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

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

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

};

