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

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

        nome_planta: data.nome_planta || null,
        descricao: data.descricao || null,
        arquivo_digital: data.arquivo_digital || null,
        formato: data.formato || null,
        data_criacao: data.data_criacao || null,
        responsavel_tecnico: data.responsavel_tecnico || null,
        georreferenciada: data.georreferenciada || false,

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

    await plantas_asbuilt_2d.setObra(data.obra || null, {
      transaction,
    });

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

    return plantas_asbuilt_2d;
  }

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

      nome_planta: item.nome_planta || null,
      descricao: item.descricao || null,
      arquivo_digital: item.arquivo_digital || null,
      formato: item.formato || null,
      data_criacao: item.data_criacao || null,
      responsavel_tecnico: item.responsavel_tecnico || null,
      georreferenciada: item.georreferenciada || false,

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

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

    // For each item created, replace relation files

    return plantas_asbuilt_2d;
  }

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

    const updatePayload = {};

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

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

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

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

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

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

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

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

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.obra !== undefined) {
      await plantas_asbuilt_2d.setObra(
        data.obra,

        { transaction },
      );
    }

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

        { transaction },
      );
    }

    return plantas_asbuilt_2d;
  }

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

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

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

    return plantas_asbuilt_2d;
  }

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

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

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

    await plantas_asbuilt_2d.destroy({
      transaction,
    });

    return plantas_asbuilt_2d;
  }

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

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

    if (!plantas_asbuilt_2d) {
      return plantas_asbuilt_2d;
    }

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

    output.obra = await plantas_asbuilt_2d.getObra({
      transaction,
    });

    output.clientes = await plantas_asbuilt_2d.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.obras,
        as: 'obra',

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

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

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

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

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

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

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

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

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

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

      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.georreferenciada) {
        where = {
          ...where,
          georreferenciada: filter.georreferenciada,
        };
      }

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

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

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