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

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

        type: data.type || null,
        platform: data.platform || null,
        serial: data.serial || null,
        asset_tag: data.asset_tag || null,
        status: data.status || null,
        encryption: data.encryption || false,

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

    await devices.setOwner(data.owner || null, {
      transaction,
    });

    await devices.setOrganizations(data.organizations || null, {
      transaction,
    });

    return devices;
  }

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

      type: item.type || null,
      platform: item.platform || null,
      serial: item.serial || null,
      asset_tag: item.asset_tag || null,
      status: item.status || null,
      encryption: item.encryption || false,

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

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

    // For each item created, replace relation files

    return devices;
  }

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

    const updatePayload = {};

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

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

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

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

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

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

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.owner !== undefined) {
      await devices.setOwner(
        data.owner,

        { transaction },
      );
    }

    if (data.organizations !== undefined) {
      await devices.setOrganizations(
        data.organizations,

        { transaction },
      );
    }

    return devices;
  }

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

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

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

    return devices;
  }

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

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

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

    await devices.destroy({
      transaction,
    });

    return devices;
  }

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

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

    if (!devices) {
      return devices;
    }

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

    output.inventory_events_device = await devices.getInventory_events_device({
      transaction,
    });

    output.owner = await devices.getOwner({
      transaction,
    });

    output.organizations = await devices.getOrganizations({
      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 userOrganizations = (user && user.organizations?.id) || null;

    if (userOrganizations) {
      if (options?.currentUser?.organizationsId) {
        where.organizationsId = options.currentUser.organizationsId;
      }
    }

    offset = currentPage * limit;

    const orderBy = null;

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

    let include = [
      {
        model: db.employees,
        as: 'owner',

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

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

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

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

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

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

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

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

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

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

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

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

        where = {
          ...where,
          organizationsId: { [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.organizationsId;
    }

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

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

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