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

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

        const credit_notes = await db.credit_notes.create(
            {
                id: data.id || undefined,
        
        credit_note_number: data.credit_note_number
        ||
        null
            ,
            
        issue_date: data.issue_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        subtotal_ht: data.subtotal_ht
        ||
        null
            ,
            
        tax_total: data.tax_total
        ||
        null
            ,
            
        total_ttc: data.total_ttc
        ||
        null
            ,
            
        reason: data.reason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await credit_notes.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await credit_notes.setInvoice( data.invoice || null, {
            transaction,
        });
        
        await credit_notes.setClient( data.client || null, {
            transaction,
        });
        

        

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

        return credit_notes;
    }
    

    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 credit_notesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                credit_note_number: item.credit_note_number
            ||
            null
            ,
            
                issue_date: item.issue_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                subtotal_ht: item.subtotal_ht
            ||
            null
            ,
            
                tax_total: item.tax_total
            ||
            null
            ,
            
                total_ttc: item.total_ttc
            ||
            null
            ,
            
                reason: item.reason
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return credit_notes;
    }

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


        

        const updatePayload = {};
        
        if (data.credit_note_number !== undefined) updatePayload.credit_note_number = data.credit_note_number;
        
        
        if (data.issue_date !== undefined) updatePayload.issue_date = data.issue_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.subtotal_ht !== undefined) updatePayload.subtotal_ht = data.subtotal_ht;
        
        
        if (data.tax_total !== undefined) updatePayload.tax_total = data.tax_total;
        
        
        if (data.total_ttc !== undefined) updatePayload.total_ttc = data.total_ttc;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await credit_notes.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.invoice !== undefined) {
            await credit_notes.setInvoice(
              
              data.invoice,
              
              { transaction }
            );
        }
        
        if (data.client !== undefined) {
            await credit_notes.setClient(
              
              data.client,
              
              { transaction }
            );
        }
        

        
        

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

        return credit_notes;
    }

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

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

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


        return credit_notes;
    }

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

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

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

        await credit_notes.destroy({
            transaction
        });

        return credit_notes;
    }

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

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

        if (!credit_notes) {
            return credit_notes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.credit_note_items_credit_note = await credit_notes.getCredit_note_items_credit_note({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await credit_notes.getOrganization({
            transaction
        });
        
        
        output.invoice = await credit_notes.getInvoice({
            transaction
        });
        
        
        output.client = await credit_notes.getClient({
            transaction
        });
        
        
        output.pdf_file = await credit_notes.getPdf_file({
            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.organizations,
        as: 'organization',
        
      },

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

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



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

    ];

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

            
            if (filter.credit_note_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'credit_notes',
                        'credit_note_number',
                        filter.credit_note_number,
                    ),
                };
            }
            
            if (filter.reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'credit_notes',
                        'reason',
                        filter.reason,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    total_ttc: {
                    ...where.total_ttc,
                            [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.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[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.credit_notes.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(
                        'credit_notes',
                        'credit_note_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

