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

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

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

    await relatorios_analiticos_video.setInspecao(data.inspecao || null, {
      transaction,
    });

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

    return relatorios_analiticos_video;
  }

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

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

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

    // For each item created, replace relation files

    return relatorios_analiticos_video;
  }

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

    const updatePayload = {};

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

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.inspecao !== undefined) {
      await relatorios_analiticos_video.setInspecao(
        data.inspecao,

        { transaction },
      );
    }

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

        { transaction },
      );
    }

    return relatorios_analiticos_video;
  }

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

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

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

    return relatorios_analiticos_video;
  }

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

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

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

    await relatorios_analiticos_video.destroy({
      transaction,
    });

    return relatorios_analiticos_video;
  }

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

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

    if (!relatorios_analiticos_video) {
      return relatorios_analiticos_video;
    }

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

    output.relatorio_andamento_atual_ultimo_relatorio_video =
      await relatorios_analiticos_video.getRelatorio_andamento_atual_ultimo_relatorio_video(
        {
          transaction,
        },
      );

    output.inspecao = await relatorios_analiticos_video.getInspecao({
      transaction,
    });

    output.clientes = await relatorios_analiticos_video.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.inspecao_aerea,
        as: 'inspecao',

        where: filter.inspecao
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.inspecao
                      .split('|')
                      .map((term) => Utils.uuid(term)),
                  },
                },
                {
                  tipo_inspecao: {
                    [Op.or]: filter.inspecao
                      .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.json_analise) {
        where = {
          ...where,
          [Op.and]: Utils.ilike(
            'relatorios_analiticos_video',
            'json_analise',
            filter.json_analise,
          ),
        };
      }

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

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

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

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

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

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