
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 Fiscal_periodsDBApi {
    

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

        const fiscal_periods = await db.fiscal_periods.create(
            {
                id: data.id || undefined,
        
        year: data.year
        ||
        null
            ,
            
        month: data.month
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        openedAt: data.openedAt
        ||
        null
            ,
            
        closedAt: data.closedAt
        ||
        null
            ,
            
        lockedAt: data.lockedAt
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await fiscal_periods.setClosedByUser( data.closedByUser || null, {
            transaction,
        });
        
        await fiscal_periods.setLockedByUser( data.lockedByUser || null, {
            transaction,
        });
        

        

        

        return fiscal_periods;
    }
    

    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 fiscal_periodsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                year: item.year
            ||
            null
            ,
            
                month: item.month
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                openedAt: item.openedAt
            ||
            null
            ,
            
                closedAt: item.closedAt
            ||
            null
            ,
            
                lockedAt: item.lockedAt
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return fiscal_periods;
    }

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

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


        

        const updatePayload = {};
        
        if (data.year !== undefined) updatePayload.year = data.year;
        
        
        if (data.month !== undefined) updatePayload.month = data.month;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.openedAt !== undefined) updatePayload.openedAt = data.openedAt;
        
        
        if (data.closedAt !== undefined) updatePayload.closedAt = data.closedAt;
        
        
        if (data.lockedAt !== undefined) updatePayload.lockedAt = data.lockedAt;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.closedByUser !== undefined) {
            await fiscal_periods.setClosedByUser(
              
              data.closedByUser,
              
              { transaction }
            );
        }
        
        if (data.lockedByUser !== undefined) {
            await fiscal_periods.setLockedByUser(
              
              data.lockedByUser,
              
              { transaction }
            );
        }
        

        
        

        

        return fiscal_periods;
    }

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

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

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


        return fiscal_periods;
    }

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

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

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

        await fiscal_periods.destroy({
            transaction
        });

        return fiscal_periods;
    }

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

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

        if (!fiscal_periods) {
            return fiscal_periods;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.closedByUser = await fiscal_periods.getClosedByUser({
            transaction
        });
        
        
        output.lockedByUser = await fiscal_periods.getLockedByUser({
            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 = [

      {
        model: db.users,
        as: 'closedByUser',
        
        where: filter.closedByUser ? {
          [Op.or]: [
            { id: { [Op.in]: filter.closedByUser.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.closedByUser.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'lockedByUser',
        
        where: filter.lockedByUser ? {
          [Op.or]: [
            { id: { [Op.in]: filter.lockedByUser.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.lockedByUser.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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


      

      



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

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

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

    
};

