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

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

        nome: data.nome || null,
        cnpj: data.cnpj || null,
        endereco: data.endereco || null,
        responsavel_tecnico: data.responsavel_tecnico || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

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

    return subcontratadas;
  }

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

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

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

    // For each item created, replace relation files

    return subcontratadas;
  }

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

    const updatePayload = {};

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

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

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

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

    updatePayload.updatedById = currentUser.id;

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

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

        { transaction },
      );
    }

    return subcontratadas;
  }

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

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

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

    return subcontratadas;
  }

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

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

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

    await subcontratadas.destroy({
      transaction,
    });

    return subcontratadas;
  }

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

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

    if (!subcontratadas) {
      return subcontratadas;
    }

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

    output.clientes = await subcontratadas.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.clientes,
        as: 'clientes',
      },
    ];

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

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

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

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

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

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

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

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