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

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

        const outlets = await db.outlets.create(
            {
                id: data.id || undefined,
        
        code: data.code
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        gps_lat: data.gps_lat
        ||
        null
            ,
            
        gps_lng: data.gps_lng
        ||
        null
            ,
            
        gps_radius_m: data.gps_radius_m
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await outlets.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return outlets;
    }
    

    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 outletsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                code: item.code
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                gps_lat: item.gps_lat
            ||
            null
            ,
            
                gps_lng: item.gps_lng
            ||
            null
            ,
            
                gps_radius_m: item.gps_radius_m
            ||
            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 outlets = await db.outlets.bulkCreate(outletsData, { transaction });

        // For each item created, replace relation files
        

        return outlets;
    }

    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 outlets = await db.outlets.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.code !== undefined) updatePayload.code = data.code;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.gps_lat !== undefined) updatePayload.gps_lat = data.gps_lat;
        
        
        if (data.gps_lng !== undefined) updatePayload.gps_lng = data.gps_lng;
        
        
        if (data.gps_radius_m !== undefined) updatePayload.gps_radius_m = data.gps_radius_m;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organizations !== undefined) {
            await outlets.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return outlets;
    }

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

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

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


        return outlets;
    }

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

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

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

        await outlets.destroy({
            transaction
        });

        return outlets;
    }

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

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

        if (!outlets) {
            return outlets;
        }

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

        
        
        
        
        
        
        output.job_positions_outlet = await outlets.getJob_positions_outlet({
            transaction
        });
        
        
        output.employees_outlet = await outlets.getEmployees_outlet({
            transaction
        });
        
        
        
        output.attendance_logs_outlet = await outlets.getAttendance_logs_outlet({
            transaction
        });
        
        
        output.attendance_requests_outlet = await outlets.getAttendance_requests_outlet({
            transaction
        });
        
        
        output.overtime_logs_outlet = await outlets.getOvertime_logs_outlet({
            transaction
        });
        
        
        output.disciplinary_actions_outlet = await outlets.getDisciplinary_actions_outlet({
            transaction
        });
        
        
        output.kpi_periods_outlet = await outlets.getKpi_periods_outlet({
            transaction
        });
        
        
        output.kpi_scores_outlet = await outlets.getKpi_scores_outlet({
            transaction
        });
        
        
        output.outlet_revenues_outlet = await outlets.getOutlet_revenues_outlet({
            transaction
        });
        
        
        output.service_charge_pools_outlet = await outlets.getService_charge_pools_outlet({
            transaction
        });
        
        
        output.loan_accounts_outlet = await outlets.getLoan_accounts_outlet({
            transaction
        });
        
        
        output.payroll_periods_outlet = await outlets.getPayroll_periods_outlet({
            transaction
        });
        
        
        output.payroll_items_outlet = await outlets.getPayroll_items_outlet({
            transaction
        });
        
        
        
        
        
        
        
        output.organizations = await outlets.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'outlets',
                        'code',
                        filter.code,
                    ),
                };
            }
            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'outlets',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'outlets',
                        'address',
                        filter.address,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


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

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

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

    
};

