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

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

        const samples = await db.samples.create(
            {
                id: data.id || undefined,
        
        sample_code: data.sample_code
        ||
        null
            ,
            
        sample_type: data.sample_type
        ||
        null
            ,
            
        drillhole_id: data.drillhole_id
        ||
        null
            ,
            
        depth_from_m: data.depth_from_m
        ||
        null
            ,
            
        depth_to_m: data.depth_to_m
        ||
        null
            ,
            
        collection_date: data.collection_date
        ||
        null
            ,
            
        lithology: data.lithology
        ||
        null
            ,
            
        alteration: data.alteration
        ||
        null
            ,
            
        geomet_domain: data.geomet_domain
        ||
        null
            ,
            
        prep_protocol: data.prep_protocol
        ||
        null
            ,
            
        qaqc_type: data.qaqc_type
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await samples.setProject( data.project || null, {
            transaction,
        });
        
        await samples.setOre_body( data.ore_body || null, {
            transaction,
        });
        
        await samples.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return samples;
    }
    

    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 samplesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                sample_code: item.sample_code
            ||
            null
            ,
            
                sample_type: item.sample_type
            ||
            null
            ,
            
                drillhole_id: item.drillhole_id
            ||
            null
            ,
            
                depth_from_m: item.depth_from_m
            ||
            null
            ,
            
                depth_to_m: item.depth_to_m
            ||
            null
            ,
            
                collection_date: item.collection_date
            ||
            null
            ,
            
                lithology: item.lithology
            ||
            null
            ,
            
                alteration: item.alteration
            ||
            null
            ,
            
                geomet_domain: item.geomet_domain
            ||
            null
            ,
            
                prep_protocol: item.prep_protocol
            ||
            null
            ,
            
                qaqc_type: item.qaqc_type
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return samples;
    }

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


        

        const updatePayload = {};
        
        if (data.sample_code !== undefined) updatePayload.sample_code = data.sample_code;
        
        
        if (data.sample_type !== undefined) updatePayload.sample_type = data.sample_type;
        
        
        if (data.drillhole_id !== undefined) updatePayload.drillhole_id = data.drillhole_id;
        
        
        if (data.depth_from_m !== undefined) updatePayload.depth_from_m = data.depth_from_m;
        
        
        if (data.depth_to_m !== undefined) updatePayload.depth_to_m = data.depth_to_m;
        
        
        if (data.collection_date !== undefined) updatePayload.collection_date = data.collection_date;
        
        
        if (data.lithology !== undefined) updatePayload.lithology = data.lithology;
        
        
        if (data.alteration !== undefined) updatePayload.alteration = data.alteration;
        
        
        if (data.geomet_domain !== undefined) updatePayload.geomet_domain = data.geomet_domain;
        
        
        if (data.prep_protocol !== undefined) updatePayload.prep_protocol = data.prep_protocol;
        
        
        if (data.qaqc_type !== undefined) updatePayload.qaqc_type = data.qaqc_type;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await samples.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.ore_body !== undefined) {
            await samples.setOre_body(
              
              data.ore_body,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await samples.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return samples;
    }

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

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

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


        return samples;
    }

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

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

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

        await samples.destroy({
            transaction
        });

        return samples;
    }

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

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

        if (!samples) {
            return samples;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.chain_of_custody_events_sample = await samples.getChain_of_custody_events_sample({
            transaction
        });
        
        
        
        
        output.metallurgical_tests_sample = await samples.getMetallurgical_tests_sample({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.project = await samples.getProject({
            transaction
        });
        
        
        output.ore_body = await samples.getOre_body({
            transaction
        });
        
        
        output.photos = await samples.getPhotos({
            transaction
        });
        
        
        output.organizations = await samples.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.projects,
        as: 'project',
        
        where: filter.project ? {
          [Op.or]: [
            { id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

            
            if (filter.sample_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'samples',
                        'sample_code',
                        filter.sample_code,
                    ),
                };
            }
            
            if (filter.drillhole_id) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'samples',
                        'drillhole_id',
                        filter.drillhole_id,
                    ),
                };
            }
            
            if (filter.lithology) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'samples',
                        'lithology',
                        filter.lithology,
                    ),
                };
            }
            
            if (filter.alteration) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'samples',
                        'alteration',
                        filter.alteration,
                    ),
                };
            }
            
            if (filter.geomet_domain) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'samples',
                        'geomet_domain',
                        filter.geomet_domain,
                    ),
                };
            }
            
            if (filter.prep_protocol) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'samples',
                        'prep_protocol',
                        filter.prep_protocol,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


      

      

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

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

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

    
};

