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

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

        const company_permits = await db.company_permits.create(
            {
                id: data.id || undefined,
        
        type: data.type
        ||
        null
            ,
            
        number: data.number
        ||
        null
            ,
            
        issuer: data.issuer
        ||
        null
            ,
            
        country_code: data.country_code
        ||
        null
            ,
            
        issued_at: data.issued_at
        ||
        null
            ,
            
        valid_from: data.valid_from
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await company_permits.setCompany( data.company || null, {
            transaction,
        });
        

        

        

        return company_permits;
    }
    

    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 company_permitsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                type: item.type
            ||
            null
            ,
            
                number: item.number
            ||
            null
            ,
            
                issuer: item.issuer
            ||
            null
            ,
            
                country_code: item.country_code
            ||
            null
            ,
            
                issued_at: item.issued_at
            ||
            null
            ,
            
                valid_from: item.valid_from
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return company_permits;
    }

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

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


        

        const updatePayload = {};
        
        if (data.type !== undefined) updatePayload.type = data.type;
        
        
        if (data.number !== undefined) updatePayload.number = data.number;
        
        
        if (data.issuer !== undefined) updatePayload.issuer = data.issuer;
        
        
        if (data.country_code !== undefined) updatePayload.country_code = data.country_code;
        
        
        if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
        
        
        if (data.valid_from !== undefined) updatePayload.valid_from = data.valid_from;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await company_permits.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        

        
        

        

        return company_permits;
    }

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

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

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


        return company_permits;
    }

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

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

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

        await company_permits.destroy({
            transaction
        });

        return company_permits;
    }

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

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

        if (!company_permits) {
            return company_permits;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await company_permits.getCompany({
            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.companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_permits',
                        'number',
                        filter.number,
                    ),
                };
            }
            
            if (filter.issuer) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_permits',
                        'issuer',
                        filter.issuer,
                    ),
                };
            }
            
            if (filter.country_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_permits',
                        'country_code',
                        filter.country_code,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_permits',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};

