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

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

        name: data.name || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    return clientes;
  }

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

      name: item.name || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * 1000),
    }));

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

    // For each item created, replace relation files

    return clientes;
  }

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

    const updatePayload = {};

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

    updatePayload.updatedById = currentUser.id;

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

    return clientes;
  }

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

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

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

    return clientes;
  }

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

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

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

    await clientes.destroy({
      transaction,
    });

    return clientes;
  }

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

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

    if (!clientes) {
      return clientes;
    }

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

    output.users_clientes = await clientes.getUsers_clientes({
      transaction,
    });

    output.cameras_ptz_clientes = await clientes.getCameras_ptz_clientes({
      transaction,
    });

    output.epcs_clientes = await clientes.getEpcs_clientes({
      transaction,
    });

    output.epis_clientes = await clientes.getEpis_clientes({
      transaction,
    });

    output.equipes_trabalho_clientes =
      await clientes.getEquipes_trabalho_clientes({
        transaction,
      });

    output.estrutura_projeto_clientes =
      await clientes.getEstrutura_projeto_clientes({
        transaction,
      });

    output.etapas_ou_trechos_clientes =
      await clientes.getEtapas_ou_trechos_clientes({
        transaction,
      });

    output.frames_imagem_clientes = await clientes.getFrames_imagem_clientes({
      transaction,
    });

    output.gemeos_digitais_clientes =
      await clientes.getGemeos_digitais_clientes({
        transaction,
      });

    output.historico_alteracoes_projeto_clientes =
      await clientes.getHistorico_alteracoes_projeto_clientes({
        transaction,
      });

    output.inspecao_aerea_clientes = await clientes.getInspecao_aerea_clientes({
      transaction,
    });

    output.maquinas_atividade_clientes =
      await clientes.getMaquinas_atividade_clientes({
        transaction,
      });

    output.materiais_atividade_clientes =
      await clientes.getMateriais_atividade_clientes({
        transaction,
      });

    output.membros_equipe_clientes = await clientes.getMembros_equipe_clientes({
      transaction,
    });

    output.memoriais_descritivos_asbuilt_clientes =
      await clientes.getMemoriais_descritivos_asbuilt_clientes({
        transaction,
      });

    output.modelos_bim_asbuilt_clientes =
      await clientes.getModelos_bim_asbuilt_clientes({
        transaction,
      });

    output.obras_cliente = await clientes.getObras_cliente({
      transaction,
    });

    output.obras_clientes = await clientes.getObras_clientes({
      transaction,
    });

    output.permissoes_modulo_clientes =
      await clientes.getPermissoes_modulo_clientes({
        transaction,
      });

    output.pessoas_atividade_clientes =
      await clientes.getPessoas_atividade_clientes({
        transaction,
      });

    output.pessoas_frame_clientes = await clientes.getPessoas_frame_clientes({
      transaction,
    });

    output.plantas_asbuilt_2d_clientes =
      await clientes.getPlantas_asbuilt_2d_clientes({
        transaction,
      });

    output.relatorio_andamento_atual_clientes =
      await clientes.getRelatorio_andamento_atual_clientes({
        transaction,
      });

    output.relatorios_analiticos_video_clientes =
      await clientes.getRelatorios_analiticos_video_clientes({
        transaction,
      });

    output.relatorios_diarios_clientes =
      await clientes.getRelatorios_diarios_clientes({
        transaction,
      });

    output.relatorios_mensais_clientes =
      await clientes.getRelatorios_mensais_clientes({
        transaction,
      });

    output.relatorios_semanais_clientes =
      await clientes.getRelatorios_semanais_clientes({
        transaction,
      });

    output.subcontratadas_clientes = await clientes.getSubcontratadas_clientes({
      transaction,
    });

    output.usuarios_cliente = await clientes.getUsuarios_cliente({
      transaction,
    });

    output.usuarios_clientes = await clientes.getUsuarios_clientes({
      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 userClientes = (user && user.clientes?.id) || null;

    if (userClientes) {
      if (options?.currentUser?.clientesId) {
        where.clientesId = options.currentUser.clientesId;
      }
    }

    offset = currentPage * limit;

    const orderBy = null;

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

    let include = [];

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

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

      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,
            },
          };
        }
      }
    }

    if (globalAccess) {
      delete where.clientesId;
    }

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

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