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

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

        const courier_profiles = await db.courier_profiles.create(
            {
                id: data.id || undefined,
        
        vehicle_type: data.vehicle_type
        ||
        null
            ,
            
        government_id_number: data.government_id_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        is_available: data.is_available
        ||
        false
        
            ,
            
        rating_average: data.rating_average
        ||
        null
            ,
            
        rating_count: data.rating_count
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await courier_profiles.setUser( data.user || null, {
            transaction,
        });
        
        await courier_profiles.setCurrent_address( data.current_address || null, {
            transaction,
        });
        
        await courier_profiles.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.courier_profiles.getTableName(),
                belongsToColumn: 'verification_files',
                belongsToId: courier_profiles.id,
            },
            data.verification_files,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.courier_profiles.getTableName(),
                belongsToColumn: 'profile_images',
                belongsToId: courier_profiles.id,
            },
            data.profile_images,
            options,
        );
        

        return courier_profiles;
    }
    

    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 courier_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                vehicle_type: item.vehicle_type
            ||
            null
            ,
            
                government_id_number: item.government_id_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                is_available: item.is_available
            ||
            false
        
            ,
            
                rating_average: item.rating_average
            ||
            null
            ,
            
                rating_count: item.rating_count
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < courier_profiles.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.courier_profiles.getTableName(),
                    belongsToColumn: 'verification_files',
                    belongsToId: courier_profiles[i].id,
                },
                data[i].verification_files,
                options,
            );
        }
        
        for (let i = 0; i < courier_profiles.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.courier_profiles.getTableName(),
                    belongsToColumn: 'profile_images',
                    belongsToId: courier_profiles[i].id,
                },
                data[i].profile_images,
                options,
            );
        }
        

        return courier_profiles;
    }

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

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


        

        const updatePayload = {};
        
        if (data.vehicle_type !== undefined) updatePayload.vehicle_type = data.vehicle_type;
        
        
        if (data.government_id_number !== undefined) updatePayload.government_id_number = data.government_id_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.is_available !== undefined) updatePayload.is_available = data.is_available;
        
        
        if (data.rating_average !== undefined) updatePayload.rating_average = data.rating_average;
        
        
        if (data.rating_count !== undefined) updatePayload.rating_count = data.rating_count;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await courier_profiles.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.current_address !== undefined) {
            await courier_profiles.setCurrent_address(
              
              data.current_address,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await courier_profiles.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.courier_profiles.getTableName(),
                belongsToColumn: 'verification_files',
                belongsToId: courier_profiles.id,
            },
            data.verification_files,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.courier_profiles.getTableName(),
                belongsToColumn: 'profile_images',
                belongsToId: courier_profiles.id,
            },
            data.profile_images,
            options,
        );
        

        return courier_profiles;
    }

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

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

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


        return courier_profiles;
    }

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

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

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

        await courier_profiles.destroy({
            transaction
        });

        return courier_profiles;
    }

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

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

        if (!courier_profiles) {
            return courier_profiles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await courier_profiles.getUser({
            transaction
        });
        
        
        output.verification_files = await courier_profiles.getVerification_files({
            transaction
        });
        
        
        output.profile_images = await courier_profiles.getProfile_images({
            transaction
        });
        
        
        output.current_address = await courier_profiles.getCurrent_address({
            transaction
        });
        
        
        output.organizations = await courier_profiles.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



      {
        model: db.file,
        as: 'verification_files',
      },

      {
        model: db.file,
        as: 'profile_images',
      },

    ];

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

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

            
            

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

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

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

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

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

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

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


      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.courier_profiles.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'courier_profiles',
                        'government_id_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

