
const db = require('../models');
const Utils = require('../utils');
const {
  getRuntimeEnvironment,
  getRuntimeProjectSlug,
} = require('./runtime-context');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class ProjectsDBApi {
    

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

        const projects = await db.projects.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        phase: data.phase
        ||
        null
            ,
            
        logo_url: data.logo_url
        ||
        null
            ,
            
        favicon_url: data.favicon_url
        ||
        null
            ,
            
        og_image_url: data.og_image_url
        ||
        null
            ,
            
        theme_config_json: data.theme_config_json
        ||
        null
            ,
            
        custom_css_json: data.custom_css_json
        ||
        null
            ,
            
        cdn_base_url: data.cdn_base_url
        ||
        null
            ,
            
        entry_page_slug: data.entry_page_slug
        ||
        null
            ,
            
        is_deleted: data.is_deleted
        ||
        false
        
            ,
            
        deleted_at_time: data.deleted_at_time
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return projects;
    }
    

    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 projectsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                phase: item.phase
            ||
            null
            ,
            
                logo_url: item.logo_url
            ||
            null
            ,
            
                favicon_url: item.favicon_url
            ||
            null
            ,
            
                og_image_url: item.og_image_url
            ||
            null
            ,
            
                theme_config_json: item.theme_config_json
            ||
            null
            ,
            
                custom_css_json: item.custom_css_json
            ||
            null
            ,
            
                cdn_base_url: item.cdn_base_url
            ||
            null
            ,
            
                entry_page_slug: item.entry_page_slug
            ||
            null
            ,
            
                is_deleted: item.is_deleted
            ||
            false
        
            ,
            
                deleted_at_time: item.deleted_at_time
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return projects;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.phase !== undefined) updatePayload.phase = data.phase;
        
        
        if (data.logo_url !== undefined) updatePayload.logo_url = data.logo_url;
        
        
        if (data.favicon_url !== undefined) updatePayload.favicon_url = data.favicon_url;
        
        
        if (data.og_image_url !== undefined) updatePayload.og_image_url = data.og_image_url;
        
        
        if (data.theme_config_json !== undefined) updatePayload.theme_config_json = data.theme_config_json;
        
        
        if (data.custom_css_json !== undefined) updatePayload.custom_css_json = data.custom_css_json;
        
        
        if (data.cdn_base_url !== undefined) updatePayload.cdn_base_url = data.cdn_base_url;
        
        
        if (data.entry_page_slug !== undefined) updatePayload.entry_page_slug = data.entry_page_slug;
        
        
        if (data.is_deleted !== undefined) updatePayload.is_deleted = data.is_deleted;
        
        
        if (data.deleted_at_time !== undefined) updatePayload.deleted_at_time = data.deleted_at_time;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return projects;
    }

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

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

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


        return projects;
    }

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

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

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

        await projects.destroy({
            transaction
        });

        return projects;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;
        const runtimeEnvironment = getRuntimeEnvironment(options);
        const runtimeProjectSlug = getRuntimeProjectSlug(options);
        const queryWhere = { ...where };

        if (runtimeEnvironment) {
            queryWhere.phase = runtimeEnvironment === 'production' 
                ? 'production' 
                : { [Op.in]: ['stage', 'production'] };
        }

        if (runtimeProjectSlug) {
            queryWhere.slug = runtimeProjectSlug;
        }

        const projects = await db.projects.findOne(
            { where: queryWhere, transaction },
        );

        if (!projects) {
            return projects;
        }

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

        
        
        
        
        
        output.project_memberships_project = await projects.getProject_memberships_project({
            transaction
        });
        
        
        output.assets_project = await projects.getAssets_project({
            transaction
        });
        
        
        
        output.presigned_url_requests_project = await projects.getPresigned_url_requests_project({
            transaction
        });
        
        
        output.tour_pages_project = await projects.getTour_pages_project({
            transaction
        });
        
        
        
        
        output.transitions_project = await projects.getTransitions_project({
            transaction
        });
        
        
        output.project_audio_tracks_project = await projects.getProject_audio_tracks_project({
            transaction
        });
        
        
        output.publish_events_project = await projects.getPublish_events_project({
            transaction
        });
        
        
        output.pwa_caches_project = await projects.getPwa_caches_project({
            transaction
        });
        
        
        output.access_logs_project = await projects.getAccess_logs_project({
            transaction
        });
        
        
        

        return output;
    }

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

        

        

        offset = currentPage * limit;

    let include = [



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.logo_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'logo_url',
                        filter.logo_url,
                    ),
                };
            }
            
            if (filter.favicon_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'favicon_url',
                        filter.favicon_url,
                    ),
                };
            }
            
            if (filter.og_image_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'og_image_url',
                        filter.og_image_url,
                    ),
                };
            }
            
            if (filter.theme_config_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'theme_config_json',
                        filter.theme_config_json,
                    ),
                };
            }
            
            if (filter.custom_css_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'custom_css_json',
                        filter.custom_css_json,
                    ),
                };
            }
            
            if (filter.cdn_base_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'cdn_base_url',
                        filter.cdn_base_url,
                    ),
                };
            }
            
            if (filter.entry_page_slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'entry_page_slug',
                        filter.entry_page_slug,
                    ),
                };
            }
            

            
            

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

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

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

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

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




            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 runtimeEnvironment = getRuntimeEnvironment(options);
        const runtimeProjectSlug = getRuntimeProjectSlug(options);

        if (runtimeEnvironment) {
            where = {
                ...where,
                phase: runtimeEnvironment,
            };
        }

        if (runtimeProjectSlug) {
            where = {
                ...where,
                slug: runtimeProjectSlug,
            };
        }
        

        

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

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

    
};
