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

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

        doc_type: data.doc_type || null,
        country: data.country || null,
        status: data.status || null,
        signed_at: data.signed_at || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

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

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

    await FileDBApi.replaceRelationFiles(
      {
        belongsTo: db.documents.getTableName(),
        belongsToColumn: 'file_ref',
        belongsToId: documents.id,
      },
      data.file_ref,
      options,
    );

    return documents;
  }

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

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

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

    // For each item created, replace relation files

    for (let i = 0; i < documents.length; i++) {
      await FileDBApi.replaceRelationFiles(
        {
          belongsTo: db.documents.getTableName(),
          belongsToColumn: 'file_ref',
          belongsToId: documents[i].id,
        },
        data[i].file_ref,
        options,
      );
    }

    return documents;
  }

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

    const updatePayload = {};

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

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

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

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

    updatePayload.updatedById = currentUser.id;

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

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

        { transaction },
      );
    }

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

        { transaction },
      );
    }

    await FileDBApi.replaceRelationFiles(
      {
        belongsTo: db.documents.getTableName(),
        belongsToColumn: 'file_ref',
        belongsToId: documents.id,
      },
      data.file_ref,
      options,
    );

    return documents;
  }

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

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

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

    return documents;
  }

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

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

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

    await documents.destroy({
      transaction,
    });

    return documents;
  }

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

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

    if (!documents) {
      return documents;
    }

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

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

    output.file_ref = await documents.getFile_ref({
      transaction,
    });

    output.organizations = await documents.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',
      },

      {
        model: db.file,
        as: 'file_ref',
      },
    ];

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

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

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

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

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

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

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

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

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

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

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