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

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

        const people = await db.people.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        known_for_department: data.known_for_department
        ||
        null
            ,
            
        birth_date: data.birth_date
        ||
        null
            ,
            
        death_date: data.death_date
        ||
        null
            ,
            
        biography: data.biography
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return people;
    }
    

    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 peopleData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                known_for_department: item.known_for_department
            ||
            null
            ,
            
                birth_date: item.birth_date
            ||
            null
            ,
            
                death_date: item.death_date
            ||
            null
            ,
            
                biography: item.biography
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return people;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.known_for_department !== undefined) updatePayload.known_for_department = data.known_for_department;
        
        
        if (data.birth_date !== undefined) updatePayload.birth_date = data.birth_date;
        
        
        if (data.death_date !== undefined) updatePayload.death_date = data.death_date;
        
        
        if (data.biography !== undefined) updatePayload.biography = data.biography;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return people;
    }

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

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

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


        return people;
    }

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

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

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

        await people.destroy({
            transaction
        });

        return people;
    }

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

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

        if (!people) {
            return people;
        }

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

        
        
        
        
        
        
        
        
        output.title_cast_person = await people.getTitle_cast_person({
            transaction
        });
        
        
        output.title_crew_person = await people.getTitle_crew_person({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.profile_images = await people.getProfile_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: 'profile_images',
      },

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'people',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.known_for_department) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'people',
                        'known_for_department',
                        filter.known_for_department,
                    ),
                };
            }
            
            if (filter.biography) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'people',
                        'biography',
                        filter.biography,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            




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

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

    
};

