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 Company_profilesDBApi {
  static async create(data, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;

    const company_profiles = await db.company_profiles.create(
      {
        id: data.id || undefined,

        legal_name: data.legal_name || null,
        address: data.address || null,
        phone: data.phone || null,
        email: data.email || null,
        website: data.website || null,
        rc: data.rc || null,
        ice: data.ice || null,
        patente: data.patente || null,
        logo_url: data.logo_url || null,
        pdf_footer: data.pdf_footer || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await company_profiles.setTenant(data.tenant || null, {
      transaction,
    });

    await company_profiles.setAgences(data.agences || null, {
      transaction,
    });

    return company_profiles;
  }

  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 company_profilesData = data.map((item, index) => ({
      id: item.id || undefined,

      legal_name: item.legal_name || null,
      address: item.address || null,
      phone: item.phone || null,
      email: item.email || null,
      website: item.website || null,
      rc: item.rc || null,
      ice: item.ice || null,
      patente: item.patente || null,
      logo_url: item.logo_url || null,
      pdf_footer: item.pdf_footer || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * 1000),
    }));

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

    // For each item created, replace relation files

    return company_profiles;
  }

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

    const updatePayload = {};

    if (data.legal_name !== undefined)
      updatePayload.legal_name = data.legal_name;

    if (data.address !== undefined) updatePayload.address = data.address;

    if (data.phone !== undefined) updatePayload.phone = data.phone;

    if (data.email !== undefined) updatePayload.email = data.email;

    if (data.website !== undefined) updatePayload.website = data.website;

    if (data.rc !== undefined) updatePayload.rc = data.rc;

    if (data.ice !== undefined) updatePayload.ice = data.ice;

    if (data.patente !== undefined) updatePayload.patente = data.patente;

    if (data.logo_url !== undefined) updatePayload.logo_url = data.logo_url;

    if (data.pdf_footer !== undefined)
      updatePayload.pdf_footer = data.pdf_footer;

    updatePayload.updatedById = currentUser.id;

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

    if (data.tenant !== undefined) {
      await company_profiles.setTenant(
        data.tenant,

        { transaction },
      );
    }

    if (data.agences !== undefined) {
      await company_profiles.setAgences(
        data.agences,

        { transaction },
      );
    }

    return company_profiles;
  }

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

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

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

    return company_profiles;
  }

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

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

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

    await company_profiles.destroy({
      transaction,
    });

    return company_profiles;
  }

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

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

    if (!company_profiles) {
      return company_profiles;
    }

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

    output.tenant = await company_profiles.getTenant({
      transaction,
    });

    output.agences = await company_profiles.getAgences({
      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 userAgences = (user && user.agences?.id) || null;

    if (userAgences) {
      if (options?.currentUser?.agencesId) {
        where.agencesId = options.currentUser.agencesId;
      }
    }

    offset = currentPage * limit;

    const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [
      {
        model: db.tenants,
        as: 'tenant',

        where: filter.tenant
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.tenant
                      .split('|')
                      .map((term) => Utils.uuid(term)),
                  },
                },
                {
                  name: {
                    [Op.or]: filter.tenant
                      .split('|')
                      .map((term) => ({ [Op.iLike]: `%${term}%` })),
                  },
                },
              ],
            }
          : {},
      },

      {
        model: db.agences,
        as: 'agences',
      },
    ];

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

      if (filter.legal_name) {
        where = {
          ...where,
          [Op.and]: Utils.ilike(
            'company_profiles',
            'legal_name',
            filter.legal_name,
          ),
        };
      }

      if (filter.address) {
        where = {
          ...where,
          [Op.and]: Utils.ilike('company_profiles', 'address', filter.address),
        };
      }

      if (filter.phone) {
        where = {
          ...where,
          [Op.and]: Utils.ilike('company_profiles', 'phone', filter.phone),
        };
      }

      if (filter.email) {
        where = {
          ...where,
          [Op.and]: Utils.ilike('company_profiles', 'email', filter.email),
        };
      }

      if (filter.website) {
        where = {
          ...where,
          [Op.and]: Utils.ilike('company_profiles', 'website', filter.website),
        };
      }

      if (filter.rc) {
        where = {
          ...where,
          [Op.and]: Utils.ilike('company_profiles', 'rc', filter.rc),
        };
      }

      if (filter.ice) {
        where = {
          ...where,
          [Op.and]: Utils.ilike('company_profiles', 'ice', filter.ice),
        };
      }

      if (filter.patente) {
        where = {
          ...where,
          [Op.and]: Utils.ilike('company_profiles', 'patente', filter.patente),
        };
      }

      if (filter.logo_url) {
        where = {
          ...where,
          [Op.and]: Utils.ilike(
            'company_profiles',
            'logo_url',
            filter.logo_url,
          ),
        };
      }

      if (filter.pdf_footer) {
        where = {
          ...where,
          [Op.and]: Utils.ilike(
            'company_profiles',
            'pdf_footer',
            filter.pdf_footer,
          ),
        };
      }

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

      if (filter.agences) {
        const listItems = filter.agences.split('|').map((item) => {
          return Utils.uuid(item);
        });

        where = {
          ...where,
          agencesId: { [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.agencesId;
    }

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

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

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