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

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

        const titles = await db.titles.create(
            {
                id: data.id || undefined,
        
        title_type: data.title_type
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        original_name: data.original_name
        ||
        null
            ,
            
        tagline: data.tagline
        ||
        null
            ,
            
        overview: data.overview
        ||
        null
            ,
            
        release_date: data.release_date
        ||
        null
            ,
            
        first_air_date: data.first_air_date
        ||
        null
            ,
            
        last_air_date: data.last_air_date
        ||
        null
            ,
            
        content_rating: data.content_rating
        ||
        null
            ,
            
        original_language: data.original_language
        ||
        null
            ,
            
        runtime_minutes: data.runtime_minutes
        ||
        null
            ,
            
        number_of_seasons: data.number_of_seasons
        ||
        null
            ,
            
        number_of_episodes: data.number_of_episodes
        ||
        null
            ,
            
        average_rating: data.average_rating
        ||
        null
            ,
            
        rating_count: data.rating_count
        ||
        null
            ,
            
        popularity_score: data.popularity_score
        ||
        null
            ,
            
        imdb_code: data.imdb_code
        ||
        null
            ,
            
        is_trending: data.is_trending
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return titles;
    }
    

    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 titlesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title_type: item.title_type
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                original_name: item.original_name
            ||
            null
            ,
            
                tagline: item.tagline
            ||
            null
            ,
            
                overview: item.overview
            ||
            null
            ,
            
                release_date: item.release_date
            ||
            null
            ,
            
                first_air_date: item.first_air_date
            ||
            null
            ,
            
                last_air_date: item.last_air_date
            ||
            null
            ,
            
                content_rating: item.content_rating
            ||
            null
            ,
            
                original_language: item.original_language
            ||
            null
            ,
            
                runtime_minutes: item.runtime_minutes
            ||
            null
            ,
            
                number_of_seasons: item.number_of_seasons
            ||
            null
            ,
            
                number_of_episodes: item.number_of_episodes
            ||
            null
            ,
            
                average_rating: item.average_rating
            ||
            null
            ,
            
                rating_count: item.rating_count
            ||
            null
            ,
            
                popularity_score: item.popularity_score
            ||
            null
            ,
            
                imdb_code: item.imdb_code
            ||
            null
            ,
            
                is_trending: item.is_trending
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return titles;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title_type !== undefined) updatePayload.title_type = data.title_type;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.original_name !== undefined) updatePayload.original_name = data.original_name;
        
        
        if (data.tagline !== undefined) updatePayload.tagline = data.tagline;
        
        
        if (data.overview !== undefined) updatePayload.overview = data.overview;
        
        
        if (data.release_date !== undefined) updatePayload.release_date = data.release_date;
        
        
        if (data.first_air_date !== undefined) updatePayload.first_air_date = data.first_air_date;
        
        
        if (data.last_air_date !== undefined) updatePayload.last_air_date = data.last_air_date;
        
        
        if (data.content_rating !== undefined) updatePayload.content_rating = data.content_rating;
        
        
        if (data.original_language !== undefined) updatePayload.original_language = data.original_language;
        
        
        if (data.runtime_minutes !== undefined) updatePayload.runtime_minutes = data.runtime_minutes;
        
        
        if (data.number_of_seasons !== undefined) updatePayload.number_of_seasons = data.number_of_seasons;
        
        
        if (data.number_of_episodes !== undefined) updatePayload.number_of_episodes = data.number_of_episodes;
        
        
        if (data.average_rating !== undefined) updatePayload.average_rating = data.average_rating;
        
        
        if (data.rating_count !== undefined) updatePayload.rating_count = data.rating_count;
        
        
        if (data.popularity_score !== undefined) updatePayload.popularity_score = data.popularity_score;
        
        
        if (data.imdb_code !== undefined) updatePayload.imdb_code = data.imdb_code;
        
        
        if (data.is_trending !== undefined) updatePayload.is_trending = data.is_trending;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return titles;
    }

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

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

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


        return titles;
    }

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

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

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

        await titles.destroy({
            transaction
        });

        return titles;
    }

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

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

        if (!titles) {
            return titles;
        }

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

        
        
        
        
        
        
        output.title_genres_title = await titles.getTitle_genres_title({
            transaction
        });
        
        
        
        output.title_cast_title = await titles.getTitle_cast_title({
            transaction
        });
        
        
        output.title_crew_title = await titles.getTitle_crew_title({
            transaction
        });
        
        
        output.videos_title = await titles.getVideos_title({
            transaction
        });
        
        
        
        output.watchlist_items_title = await titles.getWatchlist_items_title({
            transaction
        });
        
        
        output.user_ratings_title = await titles.getUser_ratings_title({
            transaction
        });
        
        
        output.recommendations_source_title = await titles.getRecommendations_source_title({
            transaction
        });
        
        output.recommendations_recommended_title = await titles.getRecommendations_recommended_title({
            transaction
        });
        
        
        output.trending_entries_title = await titles.getTrending_entries_title({
            transaction
        });
        
        
        
        output.poster_images = await titles.getPoster_images({
            transaction
        });
        
        
        output.backdrop_images = await titles.getBackdrop_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.file,
        as: 'poster_images',
      },

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

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'titles',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.original_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'titles',
                        'original_name',
                        filter.original_name,
                    ),
                };
            }
            
            if (filter.tagline) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'titles',
                        'tagline',
                        filter.tagline,
                    ),
                };
            }
            
            if (filter.overview) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'titles',
                        'overview',
                        filter.overview,
                    ),
                };
            }
            
            if (filter.original_language) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'titles',
                        'original_language',
                        filter.original_language,
                    ),
                };
            }
            
            if (filter.imdb_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'titles',
                        'imdb_code',
                        filter.imdb_code,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            release_date: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    last_air_date: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    average_rating: {
                    ...where.average_rating,
                            [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.popularity_scoreRange) {
                const [start, end] = filter.popularity_scoreRange;

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

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

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

            
            if (filter.title_type) {
                where = {
                    ...where,
                title_type: filter.title_type,
            };
            }
            
            if (filter.content_rating) {
                where = {
                    ...where,
                content_rating: filter.content_rating,
            };
            }
            
            if (filter.is_trending) {
                where = {
                    ...where,
                is_trending: filter.is_trending,
            };
            }
            




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

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

    
};

