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

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

        nome: data.nome || null,
        email: data.email || null,
        senha_hash: data.senha_hash || null,
        ativo: data.ativo || false,

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

    await usuarios.setRole(data.role || null, {
      transaction,
    });

    await usuarios.setCliente(data.cliente || null, {
      transaction,
    });

    await usuarios.setClientes(data.clientes || null, {
      transaction,
    });

    return usuarios;
  }

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

      nome: item.nome || null,
      email: item.email || null,
      senha_hash: item.senha_hash || null,
      ativo: item.ativo || false,

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

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

    // For each item created, replace relation files

    return usuarios;
  }

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

    const updatePayload = {};

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

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

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

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

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.role !== undefined) {
      await usuarios.setRole(
        data.role,

        { transaction },
      );
    }

    if (data.cliente !== undefined) {
      await usuarios.setCliente(
        data.cliente,

        { transaction },
      );
    }

    if (data.clientes !== undefined) {
      await usuarios.setClientes(
        data.clientes,

        { transaction },
      );
    }

    return usuarios;
  }

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

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

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

    return usuarios;
  }

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

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

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

    await usuarios.destroy({
      transaction,
    });

    return usuarios;
  }

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

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

    if (!usuarios) {
      return usuarios;
    }

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

    output.role = await usuarios.getRole({
      transaction,
    });

    output.cliente = await usuarios.getCliente({
      transaction,
    });

    output.clientes = await usuarios.getClientes({
      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 = [
      {
        model: db.roles,
        as: 'role',

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

      {
        model: db.clientes,
        as: 'cliente',
      },

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

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

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

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

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

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

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

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

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

      if (filter.ativo) {
        where = {
          ...where,
          ativo: filter.ativo,
        };
      }

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

        where = {
          ...where,
          clienteId: { [Op.or]: listItems },
        };
      }

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

        where = {
          ...where,
          clientesId: { [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.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.usuarios.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('usuarios', 'nome', query),
        ],
      };
    }

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

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