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

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

        const custom_artwork_requests = await db.custom_artwork_requests.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        selected_size: data.selected_size
        ||
        null
            ,
            
        selected_difficulty: data.selected_difficulty
        ||
        null
            ,
            
        estimated_color_count: data.estimated_color_count
        ||
        null
            ,
            
        estimated_price: data.estimated_price
        ||
        null
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
        ai_model_version: data.ai_model_version
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        processed_at: data.processed_at
        ||
        null
            ,
            
        approved_at: data.approved_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await custom_artwork_requests.setUser( data.user || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.custom_artwork_requests.getTableName(),
                belongsToColumn: 'source_images',
                belongsToId: custom_artwork_requests.id,
            },
            data.source_images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.custom_artwork_requests.getTableName(),
                belongsToColumn: 'pattern_files',
                belongsToId: custom_artwork_requests.id,
            },
            data.pattern_files,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.custom_artwork_requests.getTableName(),
                belongsToColumn: 'pattern_preview_images',
                belongsToId: custom_artwork_requests.id,
            },
            data.pattern_preview_images,
            options,
        );
        

        return custom_artwork_requests;
    }
    

    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 custom_artwork_requestsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                selected_size: item.selected_size
            ||
            null
            ,
            
                selected_difficulty: item.selected_difficulty
            ||
            null
            ,
            
                estimated_color_count: item.estimated_color_count
            ||
            null
            ,
            
                estimated_price: item.estimated_price
            ||
            null
            ,
            
                instructions: item.instructions
            ||
            null
            ,
            
                ai_model_version: item.ai_model_version
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                processed_at: item.processed_at
            ||
            null
            ,
            
                approved_at: item.approved_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return custom_artwork_requests;
    }

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

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.selected_size !== undefined) updatePayload.selected_size = data.selected_size;
        
        
        if (data.selected_difficulty !== undefined) updatePayload.selected_difficulty = data.selected_difficulty;
        
        
        if (data.estimated_color_count !== undefined) updatePayload.estimated_color_count = data.estimated_color_count;
        
        
        if (data.estimated_price !== undefined) updatePayload.estimated_price = data.estimated_price;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        if (data.ai_model_version !== undefined) updatePayload.ai_model_version = data.ai_model_version;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.processed_at !== undefined) updatePayload.processed_at = data.processed_at;
        
        
        if (data.approved_at !== undefined) updatePayload.approved_at = data.approved_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await custom_artwork_requests.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.custom_artwork_requests.getTableName(),
                belongsToColumn: 'source_images',
                belongsToId: custom_artwork_requests.id,
            },
            data.source_images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.custom_artwork_requests.getTableName(),
                belongsToColumn: 'pattern_files',
                belongsToId: custom_artwork_requests.id,
            },
            data.pattern_files,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.custom_artwork_requests.getTableName(),
                belongsToColumn: 'pattern_preview_images',
                belongsToId: custom_artwork_requests.id,
            },
            data.pattern_preview_images,
            options,
        );
        

        return custom_artwork_requests;
    }

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

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

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


        return custom_artwork_requests;
    }

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

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

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

        await custom_artwork_requests.destroy({
            transaction
        });

        return custom_artwork_requests;
    }

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

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

        if (!custom_artwork_requests) {
            return custom_artwork_requests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ai_generation_jobs_request = await custom_artwork_requests.getAi_generation_jobs_request({
            transaction
        });
        
        
        
        
        output.user = await custom_artwork_requests.getUser({
            transaction
        });
        
        
        output.source_images = await custom_artwork_requests.getSource_images({
            transaction
        });
        
        
        output.pattern_files = await custom_artwork_requests.getPattern_files({
            transaction
        });
        
        
        output.pattern_preview_images = await custom_artwork_requests.getPattern_preview_images({
            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: '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.file,
        as: 'source_images',
      },

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

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

    ];

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

            
            if (filter.instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'custom_artwork_requests',
                        'instructions',
                        filter.instructions,
                    ),
                };
            }
            
            if (filter.ai_model_version) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'custom_artwork_requests',
                        'ai_model_version',
                        filter.ai_model_version,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    approved_at: {
                    ...where.approved_at,
                            [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.selected_size) {
                where = {
                    ...where,
                selected_size: filter.selected_size,
            };
            }
            
            if (filter.selected_difficulty) {
                where = {
                    ...where,
                selected_difficulty: filter.selected_difficulty,
            };
            }
            


      



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

        const records = await db.custom_artwork_requests.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,
        }));
    }

    
};

